Reputation: 2474
I have elements that should show or hide after the first five elements. When I click on 'Load More...' with an id #loadMore
, it will trigger to show all the elements and change the div id to #showLess
to execute a different set of action. So, when I click #showLess
to hide the rest of the thumbnails, nothing happens. The $('#showLess').click(function()
isn't executing but instead executes the $('#loadMore').click(function()
again.
Here's a jsfiddle.
jQuery:
var vidThumbnail = "";
var elements = $('.section.thumbnail .thumb > .video-thumbnail');
for (i = 0; i < 25; i++) // loop thru 25 thumbnails
{
vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';
$('.section.thumbnail .thumb').append(vidThumbnail);
if(i > 5) // when it reaches the first five thumbnails, hide the rest
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
}
$('#loadMore').click(function() // show them all
{
$('.section.thumbnail .thumb .video-thumbnail').show();
$(this).attr('id', 'showLess'); // change id to show less
$(this).text('Show Less...'); // change text value
});
$('#showLess').click(function()
{
// slice the first five, hide the rest
$(elements).slice(5).each(function(i)
{
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
});
$(this).attr('id', 'loadMore'); // change id to show less
$(this).text('Load More...'); // change text value
});
Upvotes: 0
Views: 390
Reputation: 409
var vidThumbnail = "";
var elements = $('.section.thumbnail .thumb > .video-thumbnail');
for (i = 0; i < 25; i++) // loop thru 25 thumbnails
{
vidThumbnail = '<div class="video-thumbnail">child ' + i + '</div>';
$('.section.thumbnail .thumb').append(vidThumbnail);
if(i > 5) // when it reaches the first five thumbnails, hide the rest
$('.section.thumbnail .thumb .video-thumbnail').eq(i).hide();
}
$('.test').on('click', '#loadMore', function() // show them all
{
$('.section.thumbnail .thumb .video-thumbnail').show();
$(this).attr('id', 'showLess'); // change id to show less
$(this).text('Show Less...'); // change text value
});
$('.test').on('click', '#showLess', function()
{
// slice the first five, hide the rest
var j = 6;
$('.section.thumbnail .thumb .video-thumbnail').each(function(i)
{
$('.section.thumbnail .thumb .video-thumbnail').eq(j).hide();
j++;
});
$(this).attr('id', 'loadMore'); // change id to show less
$(this).text('Load More...'); // change text value
});
Upvotes: 0
Reputation: 458
I've fixed a bit your code because you do some mistakes. Look here: https://jsfiddle.net/sbz51wdz/36/
I explain your error:
$(this).hasClass(...)
var elements = $('.section.thumbnail .thumb > .video-thumbnail');
this have to be written after the foreach cycle that generate the elements.Hope its help! :)
Upvotes: 2
Reputation: 2034
You are changing the id of the div on click so should use $(document) and bind all ids with that like
$(document).on('click', '#loadMore', function()
https://jsfiddle.net/sbz51wdz/35/
Upvotes: 0