MariaL MariaL - 4 months ago 19
jQuery Question

Add CSS class on hover using jQuery

I'm trying to add a CSS class on hover to an element using jQuery. However, the class should only be applied to the closest element with a specific class so I tried using

.next


When I add the
.next
to my code though the class isn't added anymore (it works without that part of the code). This is the code:

$j('.products_overlay').hover(function(){
$j(this).next('.hover_text').addClass('overlay_text');
}, function(){
$j(this).next('.hover_text').removeClass('overlay_text');
});


Any idea what I'm doing wrong?

This is the HTML

<div class="products_overlay">
<a href="..." title="product1" class="product-image">
<img src="...." alt="product1" class="hover_test" />
</a>
<p class="hover_text">Test</p>
</div>

Answer

Your problem is the next which only finds siblings

$j('.products_overlay').hover(function(){
    $j(this).next('.hover_text').addClass('overlay_text'); 
}, function(){
    $j(this).next('.hover_text').removeClass('overlay_text');
});

this in that case is the products_overlay div, so your .hover_text is a child and not a sibling.

To fix it use find:

$j('.products_overlay').hover(function(){
    $j(this).find('> .hover_text').addClass('overlay_text'); 
}, function(){
    $j(this).find('> .hover_text').removeClass('overlay_text');
});