jquerytwitter-bootstraptoggle

How do I get the link text value to toggle using jQuery?


I have a large block of text with half of the text hidden. I'm using a Bootstrap 5x toggle to show and hide the block of text. This works fine.

However, I am also trying to change the button text from Show more to Show less when the toggle takes place. I have some jQuery that should work but it is not. The text does not change from Show more to Show less.

Here is the Toggle code:

<div class="collapse more-collapse" id="moreContent{sub_topic:entry_id}">
    {sub_topic:more_text}
</div>
<p><a class="red more-toggler custom-toggler me-4" data-bs-toggle="collapse" data-bs-target="#moreContent{sub_topic:entry_id}" aria-controls="moreContent" aria-expanded="false" aria-label="Toggle more-content">
Show <span>more</span><span class="hidden">less</span> &#8250;</a></p>

And here is the jQuery (running jQuery 3.7.1):

$(document).ready(function() {
    $('.hidden').removeClass('hidden').hide();
    $('.toggle-text').click(function() {
    $(this).find('span').each(function() { $(this).toggle(); });
    });
});

Solution

  • Your selector may be wrong, I don't see any .toggle-text in you mark up.
    Below I used .custom-toggler from the anchor tag to set the click event handler.

    $(document).ready(function() {
        $('.hidden').removeClass('hidden').hide();
        $('.custom-toggler').click(function() {
            $(this).find('span').toggle(); 
            $(this).parent().prev().toggleClass('collapse');
        });
    });
    .collapse{
        height: 1em;
        overflow: hidden;
    }
    [id^=moreContent]{
       white-space: pre;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="collapse more-collapse" id="moreContent{sub_topic:entry_id}">What do they got? A lot of sand
    We got a hot crustacean band
    Each little clam here
    Know how to jam here
    Under the sea
    Each little slug here
    Cuttin' a rug here
    Under the sea
    Each little snail here
    Know how to wail here
    That's why it's hotter
    Under the water
    Ya we in luck here
    Down in the muck here
    Under the sea
    </div>
    <p><a class="red more-toggler custom-toggler me-4" data-bs-toggle="collapse" data-bs-target="#moreContent{sub_topic:entry_id}" aria-controls="moreContent" aria-expanded="false" aria-label="Toggle more-content">
    Show <span>more</span><span class="hidden">less</span> &#8250;</a></p>