Reputation: 306
I need to apply this little jquery function:
$(function(){
$('.trigger').click(function(){
$('.img-popup').fadeIn(500);
$('.overlay').fadeIn(500);
});
$('.overlay').click(function(){
$('.img-popup').fadeOut(500);
$('.overlay').fadeOut(500);
});
});
to a series of divs:
<td class="result" >
<div class="trigger"><b>Show image 1</b></div>
<div class="overlay"></div>
<div class="img-popup">
<img src="imageurl-1">
</div>
</td>
...
<td class="result" >
<div class="trigger"><b>Show image 2</b></div>
<div class="overlay"></div>
<div class="img-popup">
<img src="imageurl-2">
</div>
</td>
What could be the best approach?
I sense I should use an .each() somewhere, but how can I get the related div with .overlay class and related .img-popup to show?
Or maybe I could just change the $('.trigger').click(function()
and let it take only the nearest .img-popup div?
Thanks in advance.
Upvotes: 0
Views: 351
Reputation: 660
Another way:
$('.trigger').click(function(){
$(this).parent().children('.overlay').eq(0).fadeIn(500).parent().children('.img-popup').eq(0).fadeIn(500);
});
$('.overlay').click(function(){
$(this).fadeOut(500).parent().children('.img-popup').eq(0).fadeOut(500);
});
Upvotes: 0
Reputation: 16438
For the given code, you could just use siblings()
So inside of the click handlers use these to target
$(this).siblings('.img-popup');
$(this).siblings('.overlay');
if your html gets more complicated, you can use .closest()
to get the result parent, like so
var $result = $(this).closest('.result');
$result.find('.img-popup');
$result.find('.overlay');
Upvotes: 1
Reputation: 1538
You don't need to loop with each()
, just use $(this)
for the clicked button and parent selector with jQuery to find .img-popup
and .overlay
$(function(){
$('.trigger').click(function(){
var element = $(this), parent = element.parent(".result"),
img_popup = parent.find('.img-popup'),
overlay = parent.find('.overlay');
img_popup.fadeIn(500);
overlay.fadeIn(500);
});
$('.overlay').click(function(){
var element = $(this), parent = element.parent(".result"),
img_popup = parent.find('.img-popup');
img_popup.fadeOut(500);
element.fadeOut(500);
});
});
Upvotes: 1
Reputation: 1001
You can use something like this to reference to the right img:
$(".trigger").click(function(){
$(this).siblings('.img-popup').fadeIn(500);
$(this).siblings('.overlay').fadeIn(500);
}
$(".overlay").click(function(){
$(this).siblings('.img-popup').fadeOut(500);
$(this).siblings('.overlay').fadeOut(500);
}
Upvotes: 2