How can I use window.scrollY properly

Viewed 80

I just wan't to use a fixed header when the user scrolls up. but with my solution its by default fixed to the top.

if i use fixed by default it blocks the white stick at the top. i tried z-index and other things. If i give more z-index to the stick it blocks the menu. so user won't be able to click menu links.

enter image description here

can I active window.scroll after the first 50px height maybe.

enter image description here

  const [direction, setDirection] = useState("up");

let oldScrollY = 0;

  const controlDirection = () => {
    if (window.scrollY > oldScrollY) {
      setDirection("down");
    } else {
      setDirection("up");
    }
    oldScrollY = window.scrollY;
  };

 useEffect(() => {
    window.addEventListener("scroll", controlDirection);
    return () => {
      window.removeEventListener("scroll", controlDirection);
    };
  }, []);

  return (
    <header
      className={styles.navbar}
      id={
        direction === "up"
          ? `${styles.fixed_navbar}`
          : direction === "down"
          ? `${styles.transparent__nav}`
          : ""
      }
2 Answers

When your page height goes above 50, you navbar will be active and also I optimzed your code. could you please try this, thanks.

const [direction, setDirection] = useState("up");
const controlDirection = () => {
  console.log("fUNC CALLED")
  if (window.scrollY > 50) {
    console.log("FIXED NAVBAR")
    setDirection("down");
  } else {
    console.log("TRANSPARENT NAVBAR")
    setDirection("up");
  }
};

useEffect(() => {
  window.addEventListener("scroll", controlDirection);
}, []);

<header
  className={styles.ajxb_navbar}
  id={direction === "up" ? `${styles.fixed_navbar}` : `${styles.transparent__nav}`} />

You should be tracking the value for oldScrollY in state.

Related