1

My apologies if a similar question has already been asked.

I've got a class of links, each with an image and text.

<a class="link">
   <img src="//filepath">
  link text
</a>

When the user hovers over one of these links, I'd like to apply a rotate transformer to the image only. This presents me with a problem, because I can't just use css to execute this -- if I apply :hover { rotate } to the images within the link, then this effect will only occur when the user hovers over the image, but not the rest of the link.

I foolishly thought these lines of JS would save me:

    $('a.link').hover(function(){
     $('a.link img').css(
       {'-webkit-transform':'rotate(40deg)'}
     );
   });

Of course, the problem is, this applies the transformer to the entire class when the user hovers over a single link. Also, the change doesn't reverse when the user stops hovering over the link.

I have started a fiddle, but am at a loss of how to solve this. Any help would be greatly appreciated.

http://jsfiddle.net/dbudell/z38EE/

4 Answers 4

2

You need to apply on current element that is event source.

Live Demo

$('a.link').hover(function () {
  $(this).find('.square').css({
    '-webkit-transform': 'rotate(40deg)'
  });
});

You do not have img in the html on fiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

You do not have img in the html on fiddle, now I have used element with square class.
2
$('a.link').hover(function(){
   $(this).find('img').css(
   {
     '-webkit-transform':'rotate(40deg)'
   });
});

And for your fiddle:

$('a.link').hover(function(){
 $(this).find('.square').css(
   {'-webkit-transform':'rotate(40deg)'
  });
}); 

See updated fiddle

Comments

2

The other answers cover the JS/jQuery solution, but you can do this with just CSS if you have the right selector:

a.link:hover .square {
  -webkit-transform:rotate(40deg);
}

That is, any .square elements that are descendants of a.link elements being hovered will have that style applied.

Demo: http://jsfiddle.net/z38EE/4/

1 Comment

Definitely the most efficient approach.
1

You need to apply the transform to the square that is a descendant of the current target:

$('a.link').hover(function(){
    $('.square', this).css(
        {'-webkit-transform':'rotate(40deg)'}
    );
},
function(){
    $('.square', this).css(
        {'-webkit-transform':'rotate(40deg)'}
    );
}); 

Here is a demonstration: http://jsfiddle.net/ye4tk/

1 Comment

Thanks Asad! This answers my JS question but I agree with your above comment that the CSS-only solution, of which I was unaware, is the most efficient :)

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.