volna
volna

Reputation: 2610

Change text back and forth on button click

Here is some little miss understanding of how can the text of element be changed back after it was already mutated ?

$('.target').click(function() {
  
  

  if($(this).hasClass('clicked')) {
    $(this).text('ORIGINAL').toggleClass('clicked');
  }

  $(this).text('CLICKED').toggleClass('clicked');

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a class='target'>ORIGINAL</a>

Upvotes: 1

Views: 1058

Answers (2)

Pierre C.
Pierre C.

Reputation: 1430

You last line of code is triggered everytime you click. And it sets the text to CLICKED.

You just need to use else statement.

$('.target').click(function() {

  if($(this).hasClass('clicked')) {
    $(this).text('ORIGINAL').toggleClass('clicked');
  } else {
    $(this).text('CLICKED').toggleClass('clicked');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a class='target'>ORIGINAL</a>

Upvotes: 0

adeneo
adeneo

Reputation: 318182

You could store the original in jQuery's data store, and then get it back

$('.target').each(function() {
    
    $(this).data('original', $(this).text());
    
}).on('click', function() {
    $(this).toggleClass('clicked').text(function(_, txt) {
        var org = $(this).data('original');
    
        return txt === org ? 'CLICKED' : org;
    });
});
.clicked {color: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="target">Click</div>
<br/>
<div class="target">Click</div>
<br/>
<div class="target">Click</div>
<br/>
<div class="target">Click</div>
<br/>
<div class="target">Click</div>
<br/>

Upvotes: 2

Related Questions