Michael Pon Michael Pon - 3 months ago 9
jQuery Question

toggle via data id not toggling back

I have a script that hides the

.wc-gallery
onload then toggles when a
p
with the same
data-id
is clicked. Now this script works only when you first toggle the
.wc-gallery
. When you are going to toggle it back to
hide()
, it will not work.

I have multiple
.gallery-container2
declared in my HTML. Though it works fine when I have a currently active one, then click on another
p
from the other
.gallery-container2
it turns the
active
one to
hide()
then puts the recently clicked to
show()
.

HTML:

<div class="gallery-container2">
<p data-id="1723"><strong>View before and after</strong></p>
<div class="gallery-item" data-id="1723">
<div class="wc-gallery" style="display: none;"></div>
</div>
</div>


SCRIPT:

$(window).load( function() {
$(".gallery-container2 .gallery-item .wc-gallery").hide();
});
$(".gallery-container2 p").click(function() {
var id = $(this).data('id');
$(".gallery-container2").find('.gallery-item').each(function() {
$(this).find('.wc-gallery').toggle($(this).data('id') === id);
});
});

Answer

Check out the toggle definition as it doesn't take a predicate like you are passing it. http://api.jquery.com/toggle/ This will be more efficient as well as you won't have to iterate over each .gallery-item

$(".gallery-container2 p").click(function() {
    var id = $(this).data('id');
    $("[data-id=" + id + "].gallery-item .wc-gallery").toggle()
});