Skip to content

Instantly share code, notes, and snippets.

@denistrator
Created October 4, 2017 09:18
Show Gist options
  • Save denistrator/71282d2813b97a8508d76a02e64caab8 to your computer and use it in GitHub Desktop.
Save denistrator/71282d2813b97a8508d76a02e64caab8 to your computer and use it in GitHub Desktop.
JS stiky header implementation
var mobileBreackpoint = 767;
var stickyElem = $('.page-header');
var stickyElemCheckpoint = 82;
var stickyElemActiveClass = 'page-header_sticky';
var stickyElemHelperClass = 'page-header_inert-sticky';
stickyElem.addClass(stickyElemHelperClass);
$(document).ready(function() {
updateSticky();
$(window).scroll(function() {
updateSticky();
});
$(window).resize(function() {
updateSticky();
});
});
function updateSticky() {
var currentScrollPosition = $(window).scrollTop();
if (window.innerWidth <= mobileBreackpoint) { // if mobile
stickyElem.addClass(stickyElemActiveClass);
document.body.style.paddingTop = stickyElem.outerHeight(true) + "px"; // true - includeMargin
}
if (window.innerWidth > mobileBreackpoint) { //if desktop
if (currentScrollPosition > stickyElemCheckpoint) {
compensateInitialSize();
// stickyElem.addClass(stickyElemActiveClass);
}
if (currentScrollPosition <= stickyElemCheckpoint) {
compensateInitialSize();
}
}
}
function compensateInitialSize() {
stickyElem.removeClass(stickyElemActiveClass);
document.body.style.paddingTop = stickyElem.outerHeight(true) + "px"; // true - includeMargin
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment