|
| 1 | +import React, { useEffect, useState } from "react"; |
| 2 | +import { ArrowUp, ArrowDown } from "lucide-react"; |
| 3 | + |
| 4 | +const ScrollButton: React.FC = () => { |
| 5 | + const [atTop, setAtTop] = useState(true); |
| 6 | + const [atBottom, setAtBottom] = useState(false); |
| 7 | + |
| 8 | + useEffect(() => { |
| 9 | + const handleScroll = () => { |
| 10 | + const scrollY = window.scrollY; |
| 11 | + const scrollHeight = document.documentElement.scrollHeight; |
| 12 | + const windowHeight = window.innerHeight; |
| 13 | + |
| 14 | + setAtTop(scrollY < 100); // near top |
| 15 | + setAtBottom(scrollY + windowHeight >= scrollHeight - 100); // near bottom |
| 16 | + }; |
| 17 | + |
| 18 | + window.addEventListener("scroll", handleScroll); |
| 19 | + handleScroll(); // run on mount |
| 20 | + |
| 21 | + return () => window.removeEventListener("scroll", handleScroll); |
| 22 | + }, []); |
| 23 | + |
| 24 | + const scrollToTop = () => { |
| 25 | + window.scrollTo({ top: 0, behavior: "smooth" }); |
| 26 | + }; |
| 27 | + |
| 28 | + const scrollToBottom = () => { |
| 29 | + window.scrollTo({ top: document.documentElement.scrollHeight, behavior: "smooth" }); |
| 30 | + }; |
| 31 | + |
| 32 | + return ( |
| 33 | + <button |
| 34 | + onClick={atBottom ? scrollToTop : scrollToBottom} |
| 35 | + className={`fixed bottom-6 right-6 p-3 rounded-full shadow-lg transition-all duration-300 |
| 36 | + bg-gradient-to-r from-purple-600 to-blue-600 text-white hover:opacity-90 |
| 37 | + ${atTop && atBottom ? "opacity-0 pointer-events-none" : "opacity-100"}`} |
| 38 | + > |
| 39 | + {atBottom ? <ArrowUp size={30} /> : <ArrowDown size={30} />} |
| 40 | + </button> |
| 41 | + ); |
| 42 | +}; |
| 43 | + |
| 44 | +export default ScrollButton; |
0 commit comments