Making a div follow scrolls with jQuery - simple example

Making a div follow scrolls with jQuery - simple example

Last updated:

If you have a side menu on a page and want it to go down when the user scrolls down (so the he/she doesn't need to keep scrolling up and down if the page gets too lengthy), this is a simple solution.

Say your menu lives in a (or is a) div whose id is "sidebar":

There are basically two ways to do this:

CSS

  • add this css to your page

    #sidebar {
      position: fixed;
      top: 0;
    }
    

Javascript/JQuery

  • add this piece of javascript to your page:

    $(document).ready(function () { 
        var top = $('#sidebar').offset().top - parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0));
        $(window).scroll(function (event) {
            var y = $(this).scrollTop();
            //if y > top, it means that if we scroll down any more, parts of our element will be outside the viewport
            //so we move the element down so that it remains in view.
            if (y >= top) {
               var difference = y - top;
               $('#sidebar').css("top",difference);
           }
       });
    });
    
  • References