Fawn Fawn - 5 months ago 37
jQuery Question

Multiple Show More / Show Less

How can I toggle the text to be show more/show less and change the icon arrow to flip up/down?

Updated code:

JS

$('.show-more').on('click', function() {
$(this).parent('.show-more-wrapper').find('.additional-content').toggle();
$(this).text('Show Less');
$('i', this).toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
});


HTML

<div class="show-more-wrapper">
<a href="#" class="show-more">Show More<i class="glyphicon glyphicon-chevron-down"></i></a>
<div class="additional-content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>
<div class="show-more-wrapper">
<a href="#" class="show-more">Show More<i class="glyphicon glyphicon-chevron-down"></i></a>
<div class="additional-content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
</div>

Answer

You are utilizing two different means of showing and hiding when you should only be using one.

As another poster mentioned, you should have unique references to show and hide content, otherwise they all open and close together.

Take a look at the bootstrap example here if you want to use that method (no need to write any of your own javascript when using data-toggle): http://getbootstrap.com/javascript/#collapse-example-accordion

Your javascript is not working though (you might as well remove it). If you wanted to utilize javascript to have more control (and utilize "this" as you mentioned), you should remove the bootstrap data-toggle etc and write your own logic to show and hide certain content based upon selectors. Something along the lines of:

$('.show-more').on('click', function() {
  $(this).siblings('.additional-content').toggle();
});

https://jsfiddle.net/r0m4n/kppn1mww/

Notice, there is no need to iterate through each and bind to the click event. The jQuery selector binds the handler to all elements with the class automatically.