Search code examples
javascriptjqueryhtmltoggleclass

Using event ID with specific class and toggleClass


I'm using toggleClass like in the following example on the jQuery documentation page to create a "Read More"/"Read Less" solution:

http://api.jquery.com/toggleClass/

Here is the HTML code I'm using:

<span id="block1-link" class="read-more-text more">Read More</span>
<span id="block1-content" class="sh-content">1st paragraph text<span class="read-more-text"> Hide Text</span></span>

<span id="block2-link" class="read-more-text more">Read More</span>
<span id="block2-content" class="sh-content">2nd paragraph text<span class="read-more-text"> Hide Text</span></span>

And the accompanying jQuery:

    (function ($) {
        $( ".read-more-text" ).click(function() {
            $( ".sh-content" ).toggleClass( "show-text" );
            $( ".read-more-text.more" ).toggleClass( "hide-text" );
        });
    }(jQuery));

Right now, the code shows both blocks of text when I click on the "Read More" link. I'd like the click to only affect the related "block". So, if I click on the span with "block1-link", the span with "block1-content" should toggle.

The reason I'm not adding the ID directly to my jQuery code is because this needs to work for any number of link/content groupings on a page.

I'm sure it's something obvious I'm missing. I hope someone can help me correct what I've written.

Thanks!


Solution

  • Try this. You can use .on() of jquery.

    $(".read-more-text" ).on( "click", function() {
        $(this).next().toggleClass("show-text");
        $(this).toggleClass("hide-text");
    });
    

    Edit: Developing further on the same topic, i tweaked the html classes so that its cleaner and easier.

    <span id="block1-link" class="read-more">Read More</span>
    
    <span id="block1-content" class="sh-content">1st paragraph text<span class="hide-more"> Hide Text</span>
    </span>
    
    <span id="block2-link" class="read-more">Read More</span>
    
    <span id="block2-content" class="sh-content">2nd paragraph text<span class="hide-more"> Hide Text</span></span>
    
    $(".read-more" ).on( "click", function() {
        $(this).next().toggleClass("show-text");
        $(this).toggleClass("hide-text");
    });
    
    $(".hide-more" ).on( "click", function() {
        $(this).parent().toggleClass("hide-text");
        $(this).parent().prev().toggleClass("show-text");
    });