Search code examples
jqueryhtmlbuttontoggleslidetoggle

Stop Button Text Changing on All Buttons


$('.entry-content #toggle').click(function() {

var elem = $('#toggle').text();

if (elem == 'Read More') {

$('.entry #toggle').text('Read Less');

} else {

$('.entry #toggle').text('Read More'); 

}

});  

This jQuery changes the button text on all buttons on each article on the archive page. I only want it to change the button which is clicked.

<div id="toggle" class="btn">Read More</div>

<div class="text" />

Update 1 : I only want to add the button if there's 2 or more paragraphs. I assume i can use .after some how.

Update 2 :

$('#toggle').click(function() {

$(this).closest('.post').find('.text').slideToggle();

$(this).text(function( i, v ) {

   return v === 'Read More' ? 'Read Less' : 'Read More'


      });
});

Solution

  • Reference your own button inside the event.

    $('.entry-content #toggle').click(function() {
    
    var elem = $(this).text();
    
    if (elem == 'Read More') {
    
    $(this).text('Read Less');
    
    } else {
    
    $(this).text('Read More'); 
    
    }
    
    });  
    

    Ref. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this