I have this app that upon going down 500px, a scroll to top button shows up and upon going back up, it disappears. But the effect of it is quick and there's no animation to it:
JS
const ScrollTop = () => {
const [visible, setVisible] = useState(false);
// Show Button After Scrolling Down More than 500px
const toggleVisible = () => {
if (
document.body.scrollTop > 500 ||
document.documentElement.scrollTop > 500
) {
setVisible(true);
} else {
setVisible(false);
}
};
// Listen for Scrolling Event
window.addEventListener("scroll", toggleVisible);
// Get Back Top when Clicked
const handleScroll = () => {
window.scrollTo({
top: 0,
});
};
return (
<button
id="back-to-top"
style={{ display: visible ? "block" : "none" }}
onClick={handleScroll}
title="Go To Top"
>
<i className="fas fa-chevron-circle-up"></i>
</button>
);
};
CSS
#back-to-top {
background: none;
background-repeat: no-repeat;
border: none;
cursor: pointer;
overflow: hidden;
outline: none;
position: fixed;
bottom: 30px;
right: 20px;
color: rgb(255, 51, 0);
z-index: 99;
font-size: 2.5rem;
}
#back-to-top:hover {
color: rgb(255, 0, 140);
}
Is there any way in CSS and JS to add a transition effect to its behavior so it'll smoothly fade in and out?