Pavel Gospodinov
Pavel Gospodinov

Reputation: 43

Change content of a button when it is clicked in an infinite loop using jQuery

I want to create a button that changes its content when being clicked, but also when i click again the content must return to its initial look. I've managed to create a jQuery code, which changes the content, but need help for the part with the second click. My aim is this button to have two conditions and depending on the active one when being clicked to switch to the second condition.

$("#changeArrow").click(function(){
  var textShowing = true;
  if (textShowing == true){
    $("#changeArrow").html(function(){
      return "This is some text! ⊗";
      textShowing = false;
    });
  }
  else {
    $("#changeArrow").html(function(){
      return "This is some text! ⊕";
      textShowing = true;
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeArrow">This is some text! &oplus;</button>

Upvotes: 0

Views: 144

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337656

One way to do this is by providing a function to html() which checks what the current content is and returns the new content based on that, something like this:

$("#changeArrow").click(function() {
  $(this).html((i, h) => h == 'This is some text! ⊕' ? 'This is some text! ×' : 'This is some text! ⊕');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeArrow">This is some text! &oplus;</button>

However, as all you're doing is changing the icon then this could be made even simple if you add the icon using CSS. Then you can simply toggle a class on each click:

$("#changeArrow").click(function() {
  $(this).toggleClass('close');
});
#changeArrow:after {
  content: '⊕';
  margin: 0 -1px 0 4px;  
  display: inline-block;
}
#changeArrow.close:after {
  content: '×';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeArrow">This is some text!</button>

Upvotes: 2

Mamun
Mamun

Reputation: 68923

You should declare the flag variable (textShowing) outside the click event handler function. Also, you can use this keyword to refer the clicked element:

var textShowing = true;
$("#changeArrow").click(function(){
  if (textShowing == true){
    $(this).html("This is some text! &otimes;");
    textShowing = false;

  } else {
    $(this).html("This is some text! &oplus;");
    textShowing = true;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="changeArrow">This is some text! &oplus;</button>

Upvotes: 1

Related Questions