Skip to content

Instantly share code, notes, and snippets.

@shuhei
Created October 26, 2012 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuhei/3957501 to your computer and use it in GitHub Desktop.
Save shuhei/3957501 to your computer and use it in GitHub Desktop.
Make elements follow the scroll when they head-butt the top of the window
$.fn.headbutt = function (offset) {
if (offset == null) {
offset = 0;
}
this.each(function () {
var $elem = $(this)
, initialTop = $elem.offset().top
, initialPosition = $elem.css('position')
;
$window = $(window).on('scroll', function () {
if ($window.scrollTop() > initialTop - offset) {
$elem.css({ position: 'fixed', top: offset });
} else {
$elem.css({ position: initialPosition });
}
});
});
};
$('#side-menu').headbutt();
// or
$('#side-menu').headbutt($('#fixed-menu').height());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment