Reputation: 109
I'm trying to add a class so that the span text shows on hover, but only for that particular image not all images at once.
I can get it to add class to all the spans at once, but when I try to limit it to only the span being hovered nothing happens. The problem seems to be when I add .next('span') - although I don't know why.
Can anyone tell me what I'm doing wrong here?
$('.scroller-image').hover(function() {
$(this).next('span').addClass('hover');
}, function() {
$(this).next('span').removeClass('hover');
});
Here's the markup:
<div class="scroller-image">
<span>image title</span>
<img src="#" alt="#" />
</div>
Upvotes: 1
Views: 111
Reputation: 33661
next() selects the next sibling - not child elements. What you want is this children()
$(this).children('span')// <-- this find direct children spans
or find()
$(this).find('span') //<-- this finds all descendent spans
Upvotes: 9
Reputation: 186063
You don't need JavaScript for that. CSS can do this:
.scroller-image:hover span {
/* the styles from your .hover class */
}
Live demo: http://jsfiddle.net/VbZ2G/
Upvotes: 1
Reputation: 2103
Are you trying to add the "hover" class to the span that is a child of the div that is being hovered? I think .next()
goes to the sibling, why not try
.children('span')
Upvotes: 0
Reputation: 33865
You could shorten your code a bit using .toggleClass()
and by providing this
as the context for the selector. Like this:
$('.scroller-image').hover(function(e) {
$('span', this).toggleClass('hover', e.type === "mouseenter");
});
Upvotes: 1
Reputation: 16050
.next()
finds siblings, not children. Try $(this).children('span')
Upvotes: 3