Skip to content

Instantly share code, notes, and snippets.

@lyoshenka
Last active August 29, 2015 14:21
Show Gist options
  • Save lyoshenka/a44bd8184d16f1ea900e to your computer and use it in GitHub Desktop.
Save lyoshenka/a44bd8184d16f1ea900e to your computer and use it in GitHub Desktop.
Stick element to top of screen as you scroll past it.
$.fn.stickOnScroll = function() {
var $document = $(document),
element = $(this),
stuck = false,
didScroll = false,
offsetTop = parseInt(element.offset().top),
placeholder = $('<div>'),
scrollInterval = null,
stick = function() {
placeholder.css('height', element.css('height')).show();
element.css({width: element.css('width'), position: 'fixed', top: '0px'});
stuck = true;
},
unstick = function() {
placeholder.hide();
element.css({width: '', position: '', top: ''});
stuck = false;
},
scrollHandler = function() {
if (!didScroll) { return; }
didScroll = false;
var scrollTop = parseInt($document.scrollTop());
if (!stuck && offsetTop < scrollTop)
{
stick();
}
else if (stuck && offsetTop >= scrollTop)
{
unstick();
};
};
placeholder.addClass('sticky-placeholder').hide().insertAfter(element).css({
visibility: 'hidden',
height: element.css('height'),
margin: element.css('margin'),
padding: element.css('padding'),
border: element.css('border')
});
$(window).scroll(function () { // this function fires a million times, so do all the heavy lifting in scrollHandler
didScroll = true;
});
// enable
scrollInterval = setInterval(scrollHandler, 10);
// disable
//unstick();
//clearInterval(scrollInterval);
//scrollInterval = null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment