Reputation: 28138
I'm trying to use .closest
to fadeOut
an image. The image to be faded has a class of .icon
, there are multiple .icons
on the page so I wanted to use this
and .closest
to target the .icon
within the same div as the clicked element.
My JS Fiddle shows the functionality. Click the smaller square and the text fades in. https://jsfiddle.net/x9sxcLr9/
However the icon/large square should also fade out as the text fades in. This is the code for that functionality:
$(this).closest("img.icon").fadeOut( "fast", function() {});
The HTML set up uses .cross
as the event handler, so it should find the correct .icon
close by (in the same div) but it doesn't seem to find it...
<div class="">
<img class="icon" src="http://placehold.it/100x100" />
<img class="cross" src="http://placehold.it/35x35" />
...
</div>
$( ".cross" ).click(function() { ... }
Where have I gone wrong?
Upvotes: 1
Views: 69
Reputation: 135762
You're looking for .prev()
, which will match the elements before the clicked:
$(this).prev("img.icon").fadeOut( "fast", function() {});
Upvotes: 3
Reputation: 87203
You should use siblings
instead of closest
. Closest
will look for the ancestor having the given class. Since the element is the sibling of the clicked element use siblings
.
$(".cross").click(function() {
var status = $(this).parent().attr("class")
if (status == 'active') {
$(this).parent(this).removeClass("active");
} else {
$(this).parent(this).addClass("active");
$(this).siblings("img.icon").fadeOut("fast", function() {});
}
});
Demo: https://jsfiddle.net/tusharj/x9sxcLr9/1/
Upvotes: 4