Reputation: 41
works on firefox, chrome, edge. on safari the menu (navbar) appears on scrooling up, but when scrolling to the top of the page, it hides (floats up beyond window) by itself without any scrolling-down action. any ideas why?
in javascript.js:
var prevScrollPos = window.pageYOffset;
let hideNavbar = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollPos > currentScrollPos) {
document.getElementById("menu").style.top = "0";
} else {
document.getElementById("menu").style.top = "-64px";
}
prevScrollPos = currentScrollPos;
}
window.onscroll = hideNavbar;
in index.html underneath the head:
<body>
<header id="menu">
...
</header>
...
</body>
Upvotes: 3
Views: 533
Reputation: 11
If your header id="menu" is position: fixed; changing it to position: sticky; worked for me. This eliminated the element disappearing in safari. Add overflow: auto; if the background disappears.
Upvotes: 1
Reputation: 1908
I'm betting this has to do with Safari's "scroll bounce" at the top and bottom of the document. Perhaps you'd be better off adding a mouse wheel event listener?
var menu = document.getElementById("menu");
document.addEventListener("wheel", handleScroll);
function handleScrollUp() {
console.log("UP");
menu.style.top = "0";
}
function handleScrollDown() {
console.log("DOWN");
menu.style.top = "-100px";
}
function handleScroll(event) {
if ((event.wheelDelta && event.wheelDelta > 0) || event.deltaY < 0) {
handleScrollUp();
} else {
handleScrollDown();
}
}
body {
height: 3000px;
margin: 0;
font-family: sans-serif;
}
#menu {
position: fixed;
top: 0;
width: 100%;
padding: 20px;
background: lightblue;
transition: 0.2s;
}
<div id="menu">
<p>I AM A MENU: </p>
</div>
Upvotes: 1