Reputation: 55
I'm trying to specify a span to show over a link when hovered. The code I have below does this, but it does so for all links containing a span, not just the hovered item. I was wondering how I can be more specific with the code. Any help is greatly appreciated.
$('ul#portfolio a').hover(function() {
$('ul#portfolio a span').fadeIn();}, function() { $('ul#portfolio a span').fadeOut();
});
Upvotes: 0
Views: 1076
Reputation: 322462
Use this instead:
$(this).find('span').fadeIn();
// ...
$(this).find('span').fadeOut();
Here this
represents the a
element that received the event. $(this)
wraps it in a jQuery object, and the find()
[docs] method locates the nested span
element.
Full code is:
$('ul#portfolio a').hover(function() {
$(this).find('span').fadeIn();
}, function() {
$(this).find('span').fadeOut();
});
Be aware that the fadeOut()
[docs] method does more than just set the opacity. It also hides the element after the animation is done.
You may want to use the fadeTo()
[docs] method instead:
$('ul#portfolio a').hover(function() {
$(this).find('span').fadeTo( 600, 1 );
}, function() {
$(this).find('span').fadeTo( 600, 0 );
});
...or you could even do it like this:
$('img').hover(function( e ) {
$(this).fadeTo(600, e.type === 'mouseenter');
});
Upvotes: 1
Reputation: 20481
$('ul#portfolio a').hover(function() {
$('span',$(this)).fadeIn();
}, function() {
$('span',$(this)).fadeOut();
});
Upvotes: 0