jQuery – make a div stick at top on scroll

To make a div stick at top on scroll we can use css position property fixed. Here are the steps:

  1. Find initial position of div box
    var boxInitialTop = $('#stickybox').offset().top;
    
  2. Attach handler to scroll event
    $(window).scroll(function () {
      if ($(window).scrollTop() > boxInitialTop) {
        // Box's some portion or all if it have gone up the scroll view area
      }
    }
    
  3. Full code to make html div box stick at top on scroll
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <style>
    body {margin:0;}
    .box {background-color:lightgray; margin:4px; width:100%;}
    .stickybox {background-color:lightgreen;}
    </style>
    
    <div class=box id=normalbox>normal box</div>
    <div class="box stickybox" id=stickybox>sticky box</div>
    <div class=box style="height:1000px;">tall div</div>
    
    <script type="text/javascript">
    $(function() {
      var boxInitialTop = $('#stickybox').offset().top;
      $(window).scroll(function () {
        if ($(window).scrollTop() > boxInitialTop) {
          $('#stickybox').css({position: 'fixed', top: '0px'});
        } else {
          $('#stickybox').css({position: 'static'});
        }
      });
    });
    </script>
    refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments