jQuery sticky sidebar on scroll

This jQuery will make your sidebar stick when you scroll to the top by adding a class of “fixed” to the sidebar div. You can then add the appropriate css to the class to make it stick.

var top = $('.sidebar').offset().top - parseFloat($('.sidebar').css('marginTop').replace(/auto/, 0));
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();

    // whether that's below the form
    if (y >= top) {
      // if so, ad the fixed class
      $('.sidebar').addClass('fixed');
    } else {
      // otherwise remove it
      $('.sidebar').removeClass('fixed');
    }
});

 

Leave a Reply

Your email address will not be published. Required fields are marked *

12 − 3 =