Reputation: 1242
I've got a page with product images on it and above each image is a 'more info' button. When clicked there is an overlay over the image with more information. The html looks something like this:
<div class=“products_overlay overlay_test”>
<div class=“products_overlay_info”>
<div class=“product_more_info”>
<span>More Info</span>
</div>
</div>
<ul class=“hover_text”>
<li class=“product_less_info”><span>Less Info</span></li>
</ul>
</div>
Now once the overlay is visible there's another button which says 'less info' and once clicked it hides the overlay with the extra information. This is the jQuery for it:
$j('.product_more_info').on('click', function(){
$j('.product_less_info').show();
$j('.product_more_info').hide();
});
$j('.product_less_info').on('click', function(event){
event.preventDefault();
$j('.product_more_info').show();
$j('.product_less_info').hide();
});
This works, however my problem is that it's a list of products/images so when the user click 'more info' and it hides that div it hides the div for all the products/images , not just the one the user clicked on.
I've tried using .next
but with no luck.
$j('.product_more_info').on('click', function(){
$j(this).next('.product_less_info').show();
$j(this).next('.product_more_info').hide();
});
Any ideas how to achieve this?
Upvotes: 0
Views: 126
Reputation: 813
Try this
$j('.product_more_info').on('click', function(){
$j('.product_less_info', $j(this).parents('.products_overlay')).show();
$j(this).hide();
});
Upvotes: 0
Reputation: 6381
easiest way to do it is to access common ancestor using .closest(selector)
- in this case it is .products_overlay
$j('.product_more_info').on('click', function(){
$j(this).closest('.products_overlay').find('.product_less_info').show();
$j(this).hide();
});
you can also achieve this calling .parent()
two times:
$j('.product_more_info').on('click', function(){
$j(this).parent().parent().find('.product_less_info').show();
$j(this).hide();
});
but .closest(selector)
in this case is more reliable as you may change your html structure in the future a bit
Upvotes: 2