Daniel Bogre Udell
Daniel Bogre Udell

Reputation: 67

JQuery - apply CSS change to single element of a class

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/

Upvotes: 1

Views: 1384

Answers (4)

nnnnnn
nnnnnn

Reputation: 150070

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/

Upvotes: 2

user1726343
user1726343

Reputation:

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/

Upvotes: 1

Anujith
Anujith

Reputation: 9370

$('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

Upvotes: 2

Adil
Adil

Reputation: 148150

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.

Upvotes: 2

Related Questions