Search code examples
jquerycssanimationjquery-callback

jquery animation with call back function not working on scroll


Below is some part of my code I'm using jquery animation with call back function.

I want to animate header with top:-141px after a time gap this should animate and with top:-63px.

$(window).scroll(function() {
   if ($(this).scrollTop() > 1){  

   $("#header").animate({
      position: 'fixed',
      top: '-141px',
    },function(){
      $(this).animate({
        position: 'fixed',
        top: '-63px',
      })
    });
  }
});
*{
  margin:0;
  padding:0
}

#header{
  height:141px;
  background:#333;
  color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<header id="header">
  Header section
</header>

<div>
 <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>


Solution

  • The animation method does not support property like position, so use css to set it

    $(window).scroll(function() {
      if ($(this).scrollTop() > 1) {
    
        $("#header").stop(true).css({
          position: 'fixed'
        }).animate({
          top: '-141px',
        }, function() {
          $(this).animate({
            top: '-63px',
          })
        });
      }
    });
    * {
      margin: 0;
      padding: 0
    }
    #header {
      height: 141px;
      background: #333;
      color: #fff;
    }
    div {
      height: 1000px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <header id="header">
      Header section
    </header>
    
    <div>
    </div>