Skip to content

Instantly share code, notes, and snippets.

@theJasonJones
Last active February 7, 2017 19:20
Show Gist options
  • Save theJasonJones/510d2cebe69e57c4816e00aade9e22fa to your computer and use it in GitHub Desktop.
Save theJasonJones/510d2cebe69e57c4816e00aade9e22fa to your computer and use it in GitHub Desktop.
Header shrink with custom JS add/remove
//Add listener for when the user scrolls more than 64px
function init() {
window.addEventListener('scroll', function(e){
var distanceY = window.pageYOffset || document.documentElement.scrollTop, //get offset from top
distanceX = window.innerWidth, //get window width
shrinkOn = 64,
header = document.querySelector(".header");
if( distanceX > 992 ){ // Optional: Unfixes the menu at a certain break
if (distanceY > shrinkOn) {
addClass(header, "smaller");
} else {
if (hasClass(header,"smaller")) {
removeClass(header,"smaller");
}
}
}
});
}
window.onload = init();
function hasClass(el, className) {
if (el.classList)
return el.classList.contains(className)
else
return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
}
function addClass(el, className) {
if (el.classList)
el.classList.add(className)
else if (!hasClass(el, className)) el.className += " " + className
}
function removeClass(el, className) {
if (el.classList)
el.classList.remove(className)
else if (hasClass(el, className)) {
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
el.className=el.className.replace(reg, ' ')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment