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() { var parentSelector = $('.block-views .accordion ul'), controlsHTML = $('<div class="show-more"><button>Show More</button></div>'), count = $(parentSelector).children().size(); $(parentSelector).children().not(':nth-child(1), :nth-child(2), :nth-child(3)').wrapAll('<div class="slide-content" />'); $('.slide-content').hide(); if (count > 3) { $(controlsHTML).insertAfter(parentSelector); } $(".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));
source share