Reputation: 546
Quick question, I have an unordered list of "products" and I want the description to appear on a hover. This works fine, except the animation is applied to every single product at once. How do I target just the list item I'm hovering on without giving a unique ID to every single li? I'm sure the answer uses "this" but I haven't figured out how to do it successfully.
Products:
<ul id='products'>
<li>
<div class='productDesc'>
<img src = 'images/myImage1' />
<p>
Description 1...
</p>
</div>
</li>
<li>
<div class='productDesc'>
<img src = 'images/myImage2' />
<p>
Description 2...
</p>
</div>
</li>
</ul>
javascript:
$(document).ready(function() {
$('#products li').hover(function(){
$(".productDesc").fadeIn("slow");
}, function(){
$(".productDesc").fadeOut("slow");
});
});
CSS:
.productDesc{ display:none; }
Upvotes: 0
Views: 74
Reputation: 38102
You need to use $(this)
to get a reference to the hovered list item along with .find() to get the child .productDesc
inside that hovered list item:
$(document).ready(function() {
$('#products li').hover(function(){
$(this).find(".productDesc").fadeIn("slow");
}, function(){
$(this).find(".productDesc").fadeOut("slow");
});
});
You can also shorten your code using .fadeToggle() to toggle between fadeIn
and fadeOut
$(document).ready(function() {
$('#products li').hover(function(){
$(this).find(".productDesc").fadeToggle("slow");
});
});
Upvotes: 4
Reputation: 318182
$(document).ready(function() {
$('#products li').on('mouseenter mouseleave', function() {
$(".productDesc", this).fadeToggle('slow');
});
});
Upvotes: 2
Reputation: 103348
Use this
(which will be the li
you're hovering on), and find the .productDesc
within that element.
$('#products li').hover(function(){
$(this).find(".productDesc").fadeIn("slow");
}, function(){
$(this).find(".productDesc").fadeOut("slow");
});
Upvotes: 2
Reputation: 388316
this
inside the event handlers refers to the current target element, so you can find the productDesc
element within the current li
using
$(document).ready(function () {
$('#products li').hover(function () {
$(this).find(".productDesc").fadeIn("slow");
}, function () {
$(this).find(".productDesc").fadeOut("slow");
});
});
Upvotes: 1