How to use jQuery to count the number of children in one block when multiple instances of the target class are on the same page

I have a couple of blocks on a page containing a list, such as Related Blog Posts and Related Articles .

These blocks are encoded to return all results. But to ensure that the lists were not too long, I defaulted the list to display only 3 elements and worked on the "show more" button, which when pressed causes the effect of the accordion to display the remaining elements, if any.

The problem I am facing is to show more buttons, even if the block contains no more than three elements. It appears that size() counts the total number of children of both blocks, not each block separately.

Of course, I could set up 2 unique selectors and make them work. However, I would like this script to be reused without the need to always add a new selector every time I need a different accordion block.

Now that I have it, when you want to apply the effect of the accordion to a block, all you have to do is add the β€œaccordion” class to the outer shell on any block that contains an HTML list.

Here is my code.

 (function($) { $(document).ready(function() { /** * Define variables */ var parentSelector = $('.block-views .accordion ul'), controlsHTML = $('<div class="show-more"><button>Show More</button></div>'), count = $(parentSelector).children().size(); /** * Wrap all items we want to show/hide except for the first 3 */ $(parentSelector).children().not(':nth-child(1), :nth-child(2), :nth-child(3)').wrapAll('<div class="slide-content" />'); /** * Hide content that should be hidden by default */ $('.slide-content').hide(); /** * Insert open/close button if there are more than three items in list */ if (count > 3) { $(controlsHTML).insertAfter(parentSelector); } /** * Build the expanding content container and attach it to a click event */ $(".show-more button").toggle( function () { $(this).toggleClass('collapse'); $(this).text("Show Less"); $(this).parents('.item-list').find('.slide-content').slideDown(); }, function () { $(this).toggleClass('collapse'); $(this).text("Show More"); $(this).parents('.item-list').find('.slide-content').slideUp(); } ); }); }(jQuery)); 
+4
source share
1 answer

You will need to loop through the accordions and check the length of each of them:

 (function($) { $(function() { $('.block-views .accordion ul').each(function(i,elm) { var ctrl = $('<div class="show-more"><button>Show More</button></div>'), count = $(this).children().length; if (count > 3) { $(this).after(ctrl); } }); $(".show-more button").data('state', true).on('click', function () { var state = $(this).data('state'); $(this).toggleClass('collapse').text("Show "+(state?'Less':'More')); .parents('.item-list').find('.slide-content').slideToggle().data('state' !state); }); }); }(jQuery));​ 

Also note that using this method is also deprecated!

+1
source

Source: https://habr.com/ru/post/1444167/


All Articles