sklrboy sklrboy - 6 months ago 11
Javascript Question

How to add an animation/effect for changing a HTML's content?

I'm working on fading in the new content of #myform's HTML after the mail has been sent, but I cannot figure out, how to give it an animation, so it doesn't just throw out the new HTML. I'm thinking about something like this with the "fadeIn", but it doesn't work, what's the correct way of doing it?



$(document).ready(function() {

$(function() {
var newHTML = '<div class="col-sm-12 text-center" style="color:white; background-color:#6f8595; padding-bottom:15px; border-radius:5px; transition:1s;"><h3>Thank you for your message!<br />We will get back to you as soon as possible!</h3></div>';

$('#myform').validate();
$('#myform').on("submit",function(e){
e.preventDefault();
if ($(this).valid()) {
var data = $(this).serialize();
$(this).html(newHTML).fadeIn("fast");
$.post( "includes/sendmail.php", {data});
}
});
});

});




Answer

You must first hide the content of the node you just replaced for fadeIn to work properly:

$(function() {
  var newHTML = '<div class="col-sm-12 text-center" style="color:white; background-color:#6f8595; padding-bottom:15px; border-radius:5px; transition:1s;"><h3>Thank you for your message!<br />We will get back to you as soon as possible!</h3></div>';

  $('#myform').validate();
  $("#myform").on("submit", function(e) {
    if ($(this).valid()) {
      console.log("it's valid");
      var data = $(this).serialize();
      $(this).html(newHTML).hide().fadeIn();
      $.post("includes/sendmail.php", {
        data
      });
    }
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>

<form method="POST" id="myform">
  <input type="text" name="username" id="username" />
  <input type="submit" value="Submit" name="submit" class="submit" id="submit" />
</form>