Bg Opacity change on scroll

217 Views Asked by At

beginner here, developing a website with a friend who cannot help me at the moment, and, I tried to add a function for background to fade-in on scrolling the site. I tried a lot by reading on web, but can't figure out a way that would work for me, this is his/the code:

const TopbarContainer = ({ children }: { children: ReactNode }) => (
  <div className="sticky top-0 bg-orange backdrop-blur-md">
    {children}
  </div>
);

coding in typescript, tailwind, React.

tried quite a lot, please suggest me with the best function that would work with it using the following effect;

window.addEventListener('scroll',

1

There are 1 best solutions below

0
user21002669 On
import React, { useRef, useState } from "react";

const TopbarContainer = ({ children }: { children: ReactNode }) => {
  const ref = useRef<HTMLDivElement>(null);
  const [opacity, setOpacity] = useState(1);

  const handleOpacityChange = (newOpacity: number) => {
    setOpacity(newOpacity);
    ref.current!.style.opacity = newOpacity.toString();
  };

  return (
    <div
      className="sticky top-0 bg-orange backdrop-blur-md"
      ref={ref}
      style={{ opacity }}
    >
      {children}
    </div>
  );
};

this code helps, but, I want it to change the opacity of the background only. Could it be possible?