Last active
November 22, 2019 03:22
-
-
Save jasondmoss/64bfe21d0dab49d5ab2a7582ffc47924 to your computer and use it in GitHub Desktop.
Hide the header while scolling the page down; Show on scroll up or when the bottom of the page is reached.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Hide the header while scolling the page down; Show on scroll up or when the | |
* bottom of the page is reached. | |
*/ | |
// jshint esversion: 6 | |
(function (document, window, index) { | |
"use strict"; | |
const element = document.querySelector("#myHeaderElement"); | |
if (!element) { | |
return true; | |
} | |
let dHeight = 0; | |
let elHeight = 0; | |
let elTop = 0; | |
let wHeight = 0; | |
let wScrollBefore = 0; | |
let wScrollCurrent = 0; | |
let wScrollDiff = 0; | |
window.addEventListener("scroll", function () { | |
elHeight = element.offsetHeight; | |
dHeight = document.body.offsetHeight; | |
wHeight = window.innerHeight; | |
wScrollCurrent = window.pageYOffset; | |
wScrollDiff = wScrollBefore - wScrollCurrent; | |
elTop = parseInt(window.getComputedStyle(element).getPropertyValue("top")) + wScrollDiff; | |
if /* Scrolled to top. */(wScrollCurrent <= 0) { | |
element.style.top = "0px"; | |
} else if /* Scrolled up. */(wScrollDiff > 0) { | |
element.style.top = (elTop > 0 ? 0 : elTop) +"px"; | |
} else if /* Scrolled down. */(wScrollDiff < 0) { | |
if /* Scrolled to bottom. */(wScrollCurrent + wHeight >= dHeight - elHeight) { | |
element.style.top = ((elTop = wScrollCurrent + wHeight - dHeight) < 0 ? elTop : 0) +"px"; | |
} else /* Scrolled down. */{ | |
element.style.top = (Math.abs(elTop) > elHeight ? -elHeight : elTop) +"px"; | |
} | |
} | |
wScrollBefore = wScrollCurrent; | |
}); | |
}(document, window, 0)); | |
/* <> */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment