Reputation: 635
I am trying to make a Gallery where a button says "View all Photos", by clicking that box the hidden photos are expanding and button text is changing to "Hide all photos".
Then after clicking the "Hide all photos", the expanded images are collapsing properly and button text is changing to "View all Photos" . Actually I wanted to make this.
But the problem is it's working only once. When I'm trying to click "View all Photos" for second time, hidden areas are not expanding, button text is also not changing as well.
$(document).ready(function() {
//Gallery Show all photos
$('.trigger-details > button').click(function(){
$('.single-gallery-image.hidden-lg').removeClass('hidden-lg').addClass('gallery-expanded');
$(this).addClass('hide-button').text('Hide All Photos');
$('.hide-button').click(function(){
$('.gallery-expanded').removeClass('gallery-expanded').addClass('hidden-lg');
$(this).removeClass('hide-button').text('View All Photos');
});
});
});
Upvotes: 0
Views: 54
Reputation: 1204
$('.hide-button').click()
is what you use to delegate an event to a DOM element.
Then, inside of that very statement you do $(this).removeClass('hide-button')
.
Thus it loses its class, and since the first event is only delegated/invoked once, you cannot attach it a second time. You'd be better off having a single event (not nested as you have here) which controls both states.
$('.trigger-details > button').click(function(){
if ($(this).hasClass('hide-button')) {
// do your showing logic
} else {
// do your hiding logic
}
});
Upvotes: 2
Reputation: 6917
try setting your click events on a document level and not nested within the first click
$(document).on('click','.trigger-details > button', function(){
$('.single-gallery-image.hidden-lg').removeClass('hidden-lg').addClass('gallery-expanded');
$(this).addClass('hide-button').text('Hide All Photos');
});
$(document).on('click','.hide-button', function(){
$('.gallery-expanded').removeClass('gallery-expanded').addClass('hidden-lg');
$(this).removeClass('hide-button').text('View All Photos');
});
Upvotes: 1