Skip to content

Commit

Permalink
Generalised the conf of updateStickyHeader()
Browse files Browse the repository at this point in the history
  • Loading branch information
spaceo committed Aug 31, 2023
1 parent 5d699e1 commit bb11fc1
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/stories/Blocks/header/header-sticky.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
window.addEventListener("DOMContentLoaded", () => {
let scrollDirection = "up";
let lastScrollY = window.scrollY;
// Get the starting position of the header
const initialHeaderYposition = document.querySelector("header").offsetTop;
// Tweak the header position when it's down by this amount.
const headerDownTopPositionOffset = 5;
const waitPxBeforeScroll = 5;
const headerOffsetTop = document.querySelector("header").offsetTop;

const updateStickyHeader = ({
// If you want to set a custom starting position for the header.
initialHeaderYposition = null,
// Tweak the header position when it's down by this amount.
headerDownTopPositionOffset = 5,
// Wait this many pixels before showing/hiding the header.
waitPx = 5,
}) => {
// Get the starting position of the header
const headerYStartPosition = initialHeaderYposition ?? headerOffsetTop;

const updateScrollDirection = () => {
const { scrollY } = window;
// Detect if we are going up or down.
const direction = scrollY > lastScrollY ? "down" : "up";
if (
direction !== scrollDirection &&
Math.abs(scrollY - lastScrollY) > waitPxBeforeScroll
Math.abs(scrollY - lastScrollY) > waitPx
) {
scrollDirection = direction;
}
Expand All @@ -27,11 +33,9 @@ window.addEventListener("DOMContentLoaded", () => {
"header"
).style.top = `-${headerDownTopPosition}px`;
} else {
document.querySelector(
"header"
).style.top = `${initialHeaderYposition}px`;
document.querySelector("header").style.top = `${headerYStartPosition}px`;
}
};

window.addEventListener("scroll", updateScrollDirection);
window.addEventListener("scroll", updateStickyHeader);
});

0 comments on commit bb11fc1

Please sign in to comment.