please solve it if you can do, I made a function when I scroll down, I can show the "button" {this is basically an arrow which indicates from bottom to top}. I want to add another function that when I scroll down >500 it will show the button, and if I scroll up it will hide, and if I stop scrolling if my window is scrolled >500 it will show otherwise it will hide.
export default function ScrollToTop() {
const [isVisible, setIsVisible] = useState(false);
const ScrollToTop= () => {
window.scrollTo({
top: 0,
behavior: "smooth"
});
};
useEffect(() => {
// Button is displayed after scrolling for 500 pixels
const toggleVisibility = () => {
if (window.pageYOffset > 500) {
setIsVisible(true);
} else {
setIsVisible(false);
}
};
window.addEventListener("scroll", toggleVisibility);
return () => window.removeEventListener("scroll", toggleVisibility);
}, []);
return (
<div className="scroll-to-top">
{isVisible && (
<div className="top" onClick={scrollToTop}>
<div className="top_img_holder">
<Image src="/uparrow.png" width="16" height="12" alt="" />
</div>
</div>
)}
</div>
)
}
To add the behavior you described, you can try the following:
import { useState, useEffect, useRef } from "react";
export default function ScrollToTop() {
const [isVisible, setIsVisible] = useState(false);
const prevScrollPos = useRef(0);
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: "smooth"
});
};
useEffect(() => {
const toggleVisibility = () => {
const currentScrollPos = window.pageYOffset;
// Button is displayed after scrolling for 500 pixels
if (currentScrollPos > 500 && currentScrollPos > prevScrollPos.current) {
setIsVisible(true);
} else {
setIsVisible(false);
}
prevScrollPos.current = currentScrollPos;
};
window.addEventListener("scroll", toggleVisibility);
return () => window.removeEventListener("scroll", toggleVisibility);
}, [isVisible]);
return (
<div className="scroll-to-top">
{isVisible && (
<div className="top" onClick={scrollToTop}>
<div className="top_img_holder">
<Image src="/uparrow.png" width="16" height="12" alt="" />
</div>
</div>
)}
</div>
);
}