javascript - jQuery animation doesn't work properly -


i made simple animation in jquery, not working. in particular:

$(".small-header").animate({top: "0"}, 500); 

transitions faster should. looks animation works on first time. don't know why.

$(document).ready(function( $ ){      $(document).scroll(function(){          var top = $(document).scrolltop();          console.log(top);          if (top > 160)           {              $(".small-header").css("display", "block");              $(".small-header").animate({top: "0"}, 500);              $(".big-header").css("display", "none");          }          if (top < 160)          {              $(".small-header").css("top", "-5em");              $(".small-header").css("display", "none");              $(".big-header").css("display", "block");          }      });  });
body  {    height: 1000px;  }  .big-header  {      width: 100%;      min-height: 10em;      background-color: #ffffff;      border-bottom: solid #aaaaaa 1px;  }  .small-header  {      width: 100%;      height: 4em;      background-color: #ffffff;      border-bottom: solid #aaaaaa 1px;      position: fixed;      top: -5em;      left: 0;      z-index: 9999;   }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div class="big-header">  </div>  <div class="small-header">  </div>

jsfiddle

try code:

$('el').animate({left: "+=100px"}, 500); alert('debug!'); 

you see alert appears before animation ends, because animations executed asynchronously.
means element first moved 1px (for ex.), animation stops. rest of code executes, , few milliseconds later object moved 1 more pixels right. , few milliseconds later again.
animations continue after rest of code executes.

you need tell jquery want function executes after animation ends. pass function third parameter .animate() method:

$(".small-header").animate({top: "0"}, 500 // third parameter: function () {     $(".big-header").css("display", "none"); }); 

you need understand animations not built-in in javascript. jquery makes easier make them, read behind scenes here - how js animations work?


Comments