Home > Enterprise >  How can I use window.scrollY properly
How can I use window.scrollY properly

Time:06-30

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.ajxb_navbar}
      id={
        direction === "up"
          ? `${styles.fixed_navbar}`
          : direction === "down"
          ? `${styles.transparent__nav}`
          : ""
      }

CodePudding user response:

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(false);
const controlDirection = () => {
  if (window.scrollY > 50) {
    setDirection(true);
  } else {
    setDirection(false);
  }
};

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

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

CodePudding user response:

You should be tracking the value for oldScrollY in state.

  • Related