0

Using jQuery, how would I go about changing the style of the <span> element, when the image is hovered in each post?

Here is an example of the HTML structure:

<img src="#" class="postone">

<div class="description">
    <p><span class="postone"> text </span> other text </p>
</div>


<img src="#" class="posttwo">

<div class="description">
    <p><span class="posttwo"> text </span> other text </p>
</div>

Here is the jQuery I have already:

$(document).ready( function(){

    $("img").hover( function(){

        var className = $("this").attr('class');
        $("span" + className).css("color", "#fff");

    });

});
4
  • 4
    You would use CSS, probably. Why don’t you want to? Commented Jul 28, 2014 at 17:10
  • 6
    $("span" + className) should be $("span." + className) Commented Jul 28, 2014 at 17:11
  • 2
    … and $("this") should be $(this), yes, but really – use CSS. Commented Jul 28, 2014 at 17:12
  • Last time I checked, browser support for :hover is pretty good. Do you need to support IE6? Commented Jul 28, 2014 at 17:18

2 Answers 2

3

Two issues:

  1. this is a keyword, not a string, so the quotes should be removed.

    var className = $(this).attr('class');
    
  2. You're missing a period in your selector. The className value does not contain this period since the class attribute contains class names, not class selectors, so you will have to put it in the selector string yourself.

    $("span." + className).css("color", "#fff");
    

With that said, I really don't see why you couldn't do this with CSS:

img:hover + .description span {
    color: #fff;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I wasn't sure how you would do it with css - so I will be using that instead of the javascript!
Clock, how would I do it the other way round? When you hover over the <span>, the images border changes colour? -- I'm pretty sure you would just javascript
@SAMTHEMAN999: Hmm yeah, you wouldn't be able to target it using CSS then.
2
$(document).ready(function() {
    var className;
    $("img").hover(function() {
        className = $(this).attr('class');  
        $("span." + className).css("color", "#fff");
    }, function() {
        className = $(this).attr('class');
        $("span." + className).css("color", "#000");
    });
});

You are missing a . in your class selector, and you also need to remove the double quotes from $(this). Add a mouseout function also in your code.

Demo

2 Comments

It is best to explain what you changed and why, rather than have OP hunt for the changes and guess as to why they work.
@ajp15243, I have updated my answer with explanation. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.