JSFiddle - React, Tailwind, and code Playground
by phloe
HTML
<header>
<div>
Test
</div>
</header>
<div class="content">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
CSS
*, *:before, *:after {
box-sizing: inherit;
}
html {
box-sizing: border-box;
}
body {
margin: 0;
}
header {
width: 100%;
height: 38px;
}
header > div {
position: fixed;
top: 0;
left: 0;
width: 100%;
background-color: #333;
color: #FFF;
padding: 10px;
}
.content div {
min-height: 200px;
background-color: yellow;
margin: 10px;
}
JavaScript
var header = document.querySelector("header > div");
var height = header.offsetHeight;
var scrollLast = window.scrollY;
var scrollAbsolute;
var scrollStart = scrollLast;
var scrollTimer;
var HIDDEN = "HIDDEN", VISIBLE = "VISIBLE";
var scrollState = VISIBLE; // HIDDEN
var scrollType;
window.addEventListener("wheel", function (event) {
if (!scrollType) {
scrollType = "wheel";
}
scroll(window.scrollY);
});
window.addEventListener("scroll", function (event) {
if (!scrollType) {
scroll(window.scrollY);
}
});
function scroll (scrollY) {
var state = (scrollY < scrollLast)
? VISIBLE
: HIDDEN;
if (scrollState === VISIBLE && state === HIDDEN) {
scrollAbsolute = scrollY;
header.style.cssText = "position: absolute; transform: translateY(" + scrollAbsolute + "px);";
}
else if (scrollState === HIDDEN && state === VISIBLE) {
header.style.cssText = "";
}
scrollState = state;
scrollLast = scrollY;
clearTimeout(scrollTimer);
scrollTimer = setTimeout(scrollReset, 300);
}
function scrollReset () {
clearTimeout(scrollTimer);
scrollTimer = null;
scrollType = null;
if (scrollAbsolute) {
var delta = scrollLast - scrollAbsolute;
console.log(delta);
if (delta > 0) {
var y = scrollLast + ((delta < height / 2) ? -height : 0);
header.style.cssText = "position: absolute; transform: translateY(" + y + "px); transition: 1s transform;";
setTimeout(function () {
header.style.cssText = "";
}, 1500);
}
scrollAbsolute = null;
}
}