Change the text of a button

I'm doing a project that i have to change the text of a button with some fade effects. But i can't do it. I should click on the button and the text of it should fade out and them fade in with other text. I'm using jQuery for this

$("#button_fade").on("click", function(){
    if($(this).text() == "HELLO") {
         $(this).text().fadeOut(function(){
             $(this).text("WORLD").fadeIn();
         });
    }
});

I've already tried this code but it doesn't works.

Upvotes: 0

Views: 159

Answers (1)

Barmar
Barmar

Reputation: 782107

The .text() function returns a string, which doesn't have a fadeOut() method. You want to run that method on the element itself, you don't need to call .text() first.

$("#button_fade").on("click", function() {
  if ($(this).text() == "HELLO") {
    $(this).fadeOut(function() {
      $(this).text("WORLD").fadeIn();
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button_fade">HELLO</button>

If your intent was to just fade out the text, not the whole button, you need to put an element inside the button and perform the fade effect on that.

$("#button_fade").on("click", function() {
  if ($(this).text() == "HELLO") {
    $(this).children("span").fadeOut(function() {
      $(this).text("WORLD").fadeIn();
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button_fade"><span>HELLO</span></button>

Upvotes: 1

Related Questions