How can I change the value of an element smoothly?

Here is my code:

$('button').on('click', function(){
  $('div').html('<p>something new!</p>').fadeIn(1000);
});
div{
  border: 1px solid gray;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p>something<p>
</div>
<br>
<button>change div's value</button>

As you see, I've used fadeIn() to make replacing-value-operation smoothly. But still replacement happens quickly. How can I apply an effect on it?

Answers 1

  • Something like this ?

    $('button').on('click', function(){
      var replacingDiv = $('div.replace');
      
      $(replacingDiv).fadeOut(500);
      setTimeout(function(){
        $(replacingDiv).html('changed').fadeIn(1000);
      }, 500);
    });
    div{
      border: 1px solid gray;
      text-align: center;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="replace">
      <p>something<p>
    </div>
    <br>
    <button>change div's value</button>


Related Articles