Ashonko
Ashonko

Reputation: 623

How to make fade in and out transition of jQuery innerHTML change

I have the following simple button that toggles the innerHTML text. I have been looking for a slow fade in and fade out transition for the change of innerHTML on click but haven't have a good luck doing that. Can you please help me out how I may achieve that?

Thanks in advance for your suggestion.

var Chg;
var Btn = document.getElementById("change");

$("#change").click(function() {
    Chg = !Chg;
    if (Chg) {
        Btn.innerHTML = "Toggled";
    } else {
        Btn.innerHTML = "Not Toggled";
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="change">Not Toogled</button>

Upvotes: 0

Views: 431

Answers (2)

Nick
Nick

Reputation: 16576

Here's a potential solution, which may work depending on what effect you're going for.

var Chg;

$("#change").click(function() {
    Chg = !Chg;
    var text;
    if (Chg) {
        text = "Toggled";
    } else {
        text = "Not Toggled";
    }
    $(this).fadeOut("fast", function() {
        this.innerHTML = text;
        $(this).fadeIn("fast");
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="change">Not Toggled</button>

Upvotes: 2

Farhad Bagherlo
Farhad Bagherlo

Reputation: 6699

$("#change").on('click',function() {
    var $this=$(this);
    var x,x1;
    if($this.attr("data-Toggle")=="0"){
       x="span:first-child";
       x1="span:last-child";
       $this.attr("data-Toggle","1");
    }
    else{
       x="span:last-child";
       x1="span:first-child";
       $this.attr("data-Toggle","0");
    }
    $this.find(x).fadeToggle(500);
    setTimeout(function(){ 
     $this.find(x1).fadeToggle();
    }, 500);
});
button{width:100px;height:20px;}
button span:last-child{display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button data-Toggle="0" id="change">
<span>Not Toggled</span>
<span>Toggled</span>
</button>

Upvotes: 1

Related Questions