123movies-seo/resources/js/components/scroll_to_top.js

40 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2024-08-24 23:08:42 +03:00
import { isNull, debounce } from "lodash";
function scrollHandler(backToTop, header) {
const classToggle = "opacity-0",
headerClsToggle = 'bg-opacity-70';
if (window.pageYOffset > 100) {
if (backToTop.classList.contains(classToggle)) {
backToTop.classList.remove(classToggle);
}
if (!header.classList.contains(headerClsToggle)) {
header.classList.add(headerClsToggle);
}
} else {
if (!backToTop.classList.contains(classToggle)) {
backToTop.classList.add(classToggle);
}
if (header.classList.contains(headerClsToggle)) {
header.classList.remove(headerClsToggle);
}
}
}
export function initialize() {
const backToTop = document.getElementById("back-top"),
header = document.getElementById("header"),
debouncedScrollHandler = debounce(scrollHandler, 100);
if (!isNull(backToTop)) {
window.addEventListener("scroll", () =>
debouncedScrollHandler(backToTop, header)
);
backToTop.addEventListener("click", () =>
window.scrollTo({
top: 0,
behavior: "smooth",
})
);
}
}