Reputation: 19
I wrote a jquery for show more and show less item. It works fine only for first item. But when I am going another item and select to show more item. It's not working. I understand that when I am switching another item then jquery load and display: hide previous section and display: block corrent section. That's why my jquery not working on for hidden section. Can anyone help me to solve this problem, please? Thanks.
This is my Code.
var item_length = $('.button_img_custom_class .buttonSelectionItemContainer .ButtonSelectorItem').length;
var target = $('.button_img_custom_class .buttonSelectionItemContainer');
$(target).each(function () {
$(this).toggleClass("example");
var items = $(this).children().length;
if (items > 6) {
$(this).css({'max-height': '115px', 'overflow': 'hidden'});
$(this).after('<a id="show-more">Show More</a>');
}
;
})
$('#show-more').click(function () {
if ($(this).prev().hasClass('open')) {
$(this).prev().removeClass('open');
$('#show-more').html('Show More');
$(this).prev().css({'max-height': '115px'});
} else {
$(this).prev().addClass('open');
$('#show-more').html('Show Less');
$(this).prev().css({'max-height': '1000px'});
}
})
Upvotes: 1
Views: 21
Reputation: 218827
You're doing this in a loop:
$(this).after('<a id="show-more">Show More</a>');
Which means you're creating multiple elements with the same id
, which is invalid.
It works fine only for first item.
Because there's no reason for jQuery, JavaScript, the browser, etc. to ever look for another #show-more
element once it's found the element with that id
. There shouldn't be another one.
Instead of an id
, use a class
:
$(this).after('<a class="show-more">Show More</a>');
And bind the click handler to that class:
$('.show-more').click(function () {
if ($(this).prev().hasClass('open')) {
$(this).prev().removeClass('open');
$(this).html('Show More');
$(this).prev().css({'max-height': '115px'});
} else {
$(this).prev().addClass('open');
$(this).html('Show Less');
$(this).prev().css({'max-height': '1000px'});
}
})
Upvotes: 0