Sam Provides
Sam Provides

Reputation: 259

Jquery addclass on hover

I have this structure

<div class="container">
  <a> <img /> </a>
  <div id="actions"></div>
 <ul id="add-to"> </ul>
</div>

and I'm using a script like this

<script>
jQuery(function() {
    jQuery("#actions, #add-to").hover(function(){
        jQuery(this).prev('a').addClass('opacity');
    }, function() {
        jQuery(this).prev('a').removeClass('opacity');
    });
});
</script>

it does work when hover on the actions element id, but not with the #add-to.

Can you help me with this? thanks

Upvotes: 0

Views: 75

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115282

prev() only select immediate previous element, a is not immediately previous to#add-to. In this case you can use siblings() or prevAll() . while using prevAll() use first() to get closest one

<script>
jQuery(function() {
    jQuery("#actions, #add-to").hover(function(){
        jQuery(this).siblings('a').addClass('opacity');
    }, function() {
        jQuery(this).siblings('a').removeClass('opacity');
    });
});
</script>

or

<script>
jQuery(function() {
    jQuery("#actions, #add-to").hover(function(){
        jQuery(this).prevAll('a').first().addClass('opacity');
    }, function() {
        jQuery(this).prevAll('a').first().removeClass('opacity');
    });
});
</script>

Upvotes: 1

Related Questions