Skip to content

Instantly share code, notes, and snippets.

@manfromanotherland
Last active August 29, 2015 13:55
Show Gist options
  • Save manfromanotherland/8714353 to your computer and use it in GitHub Desktop.
Save manfromanotherland/8714353 to your computer and use it in GitHub Desktop.
JS, jQuery: Sticky element on top. #snippet
// Sticky Element on scroll
var sticky = $('.selector');
var top = sticky.offset().top - parseFloat(sticky.css('margin-top').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();
y >= top ? sticky.addClass('fixed') : sticky.removeClass('fixed');
});
// Sticky Element on scroll
var sticky = document.querySelector('.selector');
var origOffsetY = sticky.offsetTop;
function onScroll(e) {
window.scrollY >= origOffsetY ? sticky.classList.add('fixed') : sticky.classList.remove('fixed');
}
document.addEventListener('scroll', onScroll);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment