Skip to content

Commit 06d2321

Browse files
committed
Navbar scrolling improvement.
1 parent b65daf4 commit 06d2321

File tree

1 file changed

+28
-13
lines changed

1 file changed

+28
-13
lines changed

src/components/Header.astro

Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -47,26 +47,41 @@ import links from "@data/links.json";
4747
<Search />
4848

4949
<script>
50-
let prevScrollPos = window.pageYOffset;
51-
const navbar = document.getElementById("navbar") as HTMLElement;
52-
53-
window.addEventListener("scroll", () => {
54-
let currentScrollPos = window.pageYOffset;
55-
if (prevScrollPos > currentScrollPos) {
56-
navbar.style.transform = "translateY(0)";
57-
} else {
58-
navbar.style.transform = "translateY(-100%)";
50+
document.addEventListener("DOMContentLoaded", function() {
51+
let prevScrollPos = window.scrollY || window.pageYOffset;
52+
const navbar = document.getElementById("navbar");
53+
54+
if (!navbar) return;
55+
56+
let ticking = false;
57+
58+
window.addEventListener("scroll", function() {
59+
if (!ticking) {
60+
window.requestAnimationFrame(function() {
61+
let currentScrollPos = window.scrollY || window.pageYOffset;
62+
63+
if (prevScrollPos > currentScrollPos) {
64+
navbar.style.transform = "translateY(0)";
65+
} else {
66+
navbar.style.transform = "translateY(-100%)";
67+
}
68+
69+
prevScrollPos = currentScrollPos;
70+
ticking = false;
71+
});
72+
73+
ticking = true;
5974
}
60-
prevScrollPos = currentScrollPos;
6175
});
6276

63-
navbar.addEventListener("focusin", () => {
77+
navbar.addEventListener("focusin", function() {
6478
navbar.style.transform = "translateY(0)";
6579
});
6680

67-
navbar.addEventListener("focusout", () => {
68-
if (window.pageYOffset > 100) {
81+
navbar.addEventListener("focusout", function() {
82+
if ((window.scrollY || window.pageYOffset) > 100) {
6983
navbar.style.transform = "translateY(-100%)";
7084
}
7185
});
86+
});
7287
</script>

0 commit comments

Comments
 (0)