There are times when you may want your website’s header to appear only when users scroll up, keeping it hidden while scrolling down. This feature is particularly useful for creating a cleaner and more focused browsing experience.
To achieve this effect, you can use the code snippet below. Just make sure to assign a specific height and an ID (#hide-header
) to your header container for it to work correctly.
<script>
var prevScrollpos = window.pageYOffset;
window.onscroll = function () {
var currentScrollPos = window.pageYOffset;
var adminBarHeight = document.getElementById("wpadminbar") ? document.getElementById("wpadminbar").offsetHeight : 0;
if (prevScrollpos > currentScrollPos) {
// Show the header and account for the admin bar if it exists
document.getElementById("hide-header").style.top = adminBarHeight + "px";
} else {
// Hide the header
document.getElementById("hide-header").style.top = "-80px"; // header height
}
prevScrollpos = currentScrollPos;
};
</script>