Amit Dhamu

Writes Code

Fixed Position on Scroll

Nightmare to implement but found one by the great Chris Coyier at CSS-Tricks.com.

$(function() {

    var $sidebar   = $("#sidebar"),
        $window    = $(window),
        offset     = $sidebar.offset(),
        topPadding = 15;

    $window.scroll(function() {
        if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                marginTop: $window.scrollTop() - offset.top + topPadding
            });
        } else {
            $sidebar.stop().animate({
                marginTop: 0
            });
        }
    });

});


A second example from the equally great Remy Sharp on jQuery for Designers which mimics the Apple Store with no animation on scroll.

// CSS
.fixed {
     position: fixed;
}

// jQuery
var top = $("#sidebar").offset().top - parseFloat($("#sidebar").css("marginTop").replace(/auto/, 0));

$(window).scroll(function (event) {
     var y = $(this).scrollTop();

     if (y >= (top-20)) {
          $("#sidebar").addClass("fixed");
     } else {
          $("#sidebar").removeClass("fixed");
     }
});


fixed position / scroll / jquery

← Multiples Of On The Fly Thumbnails →