Skip to content

Commit

Permalink
fix(scroll): fix Optimisation
Browse files Browse the repository at this point in the history
  • Loading branch information
Shariq2003 committed Oct 9, 2024
1 parent 25e199a commit 327feeb
Showing 1 changed file with 17 additions and 23 deletions.
40 changes: 17 additions & 23 deletions components/basic/MoveToTop.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,41 @@
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import { FaArrowCircleUp } from "react-icons/fa";

const ScrollButton = () => {
const [visible, setVisible] = useState(false);
const [isVisible, setIsVisible] = useState(false);

const toggleVisible = () => {
const scrolled = document.documentElement.scrollTop;
const topBtn = document.getElementById("top-btn");
if (scrolled > 300) {
setVisible(true);
topBtn.classList.add("tw-opacity-100");
} else if (scrolled <= 300) {
topBtn.classList.remove("tw-opacity-100");
setTimeout(() => {
setVisible(false);
}, 100);
}
};
useEffect(() => {
const handleScroll = () => {
setIsVisible(window.scrollY > 300);
};
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
}, []);

const scrollToTop = () => {
const scrollDuration = 500;
const scrollStep = -window.scrollY / (scrollDuration / 15);
const scrollStep = -window.scrollY / 15;
const scrollInterval = setInterval(() => {
if (window.scrollY === 0) {
clearInterval(scrollInterval);
clearInterval(scrollInterval);
} else {
window.scrollBy(0, scrollStep);
window.scrollBy(0, scrollStep);
}
}, 15);
};

window.addEventListener("scroll", toggleVisible);

return (
<div
id="top-btn"
className="tw-flex tw-opacity-0 tw-flex-col tw-z-[1000] tw-text-center tw-text-[#845ec2] tw-fixed tw-bottom-0 tw-right-0 tw-mr-8 tw-mb-8 tw-cursor-pointer hover:tw-text-blue-500 tw-duration-300 tw-transition-all"
className={`tw-fixed tw-bottom-8 tw-right-8 tw-z-50 tw-cursor-pointer tw-text-[#845ec2] hover:tw-text-blue-500 tw-opacity-0 transition-opacity duration-300 ${isVisible ? "tw-opacity-100" : ""
}`}
style={{ pointerEvents: isVisible ? "auto" : "none" }}
>
<FaArrowCircleUp
onClick={scrollToTop}
className="tw-bg-white tw-rounded-full"
fontSize={45}
style={{ display: visible ? "inline" : "none" }}
/>
</div>
);
Expand Down

0 comments on commit 327feeb

Please sign in to comment.