d
Amit DhamuSoftware Engineer
 

Fixed Position on Scroll

2 minute read 00000 views

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.

.fixed {
  position: fixed;
}
var top =
  $('#sidebar').offset().top -
  parseFloat($('#sidebar').css('marginTop').replace(/auto/, 0))

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

  $('#sidebar').toggleClass('fixed', y >= top - 20)
})