0
$('.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'


      });
});
Dev
  • 457
  • 6
  • 18

3 Answers3

1

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

dvr
  • 885
  • 5
  • 20
  • Wish i understood jQuery like you Diego . I've spent 2 days trying to learn. Thank you very much. – Dev Sep 28 '17 at 03:31
  • Glad i could help, and keep learning! JS is an awesome puzzle to work with! – dvr Sep 28 '17 at 03:33
  • Just 1 more question if you have time please. I only want to add the button if there's 2 or more paragraphs. I assume i can use .after some how. – Dev Sep 28 '17 at 03:45
  • You could use the length of your text or you can dig into this question https://stackoverflow.com/questions/3336264/paragraphs-in-javascript – dvr Sep 28 '17 at 03:51
1

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

    var elem = $(this).text();

    if (elem == 'Read More') {
        $(this).text('Read Less');
    } else {
        $(this).text('Read More'); 
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toggle" class="btn">Read More</div>

<div class="text" />
Saw Zin Min Tun
  • 642
  • 3
  • 9
1

Simplified code.

$('#toggle').click(function() {
    $(this).text(function(i, v){
       return v === 'Read More' ? 'Read Less' : 'Read More'
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toggle" class="btn">Read More</div>

<div class="text" />