Skip to content

Instantly share code, notes, and snippets.

@biantris
Last active July 5, 2022 21:59
Show Gist options
  • Save biantris/a8ca46f2e63497ea27b89250c92e3e05 to your computer and use it in GitHub Desktop.
Save biantris/a8ca46f2e63497ea27b89250c92e3e05 to your computer and use it in GitHub Desktop.
dinamic-btn-scroll with tailwind css
const [positionButtonDynamic, setPositionButtonDynamic] = useState('bottom-23');
  const [scrollTop, setScrollTop] = useState(0);

  useEffect(() => {
    const onScroll = e => setScrollTop(e.target.documentElement.scrollTop);

    window.addEventListener("scroll", onScroll);

    return () => window.removeEventListener("scroll", onScroll);
  }, [scrollTop]);

  useEffect(() => {
    if(scrollTop > 0) setPositionButtonDynamic('bottom-0');
    if(scrollTop === 0) setPositionButtonDynamic('bottom-23');
  }, [scrollTop])

  const cssPositionButtonDynamic =  `btn md:hidden sm:block fixed w-screen m-0 h-[52px] mr-20 transition delay-15 text-center flex justify-center items-center rounded-none -ml-[18px] -mt-[52px] z-20 ${positionButtonDynamic}`
  <Link href="https://test.com">
    <a target="_blank" className={cssPositionButtonDynamic}>
      Button text
    </a>
  </Link>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment