webdlh-net/wwwroot/js/scroll-snap.js

97 lines
2.4 KiB
JavaScript

document.addEventListener("DOMContentLoaded", function () {
let isScrolling = false;
let currentSection = 0;
const sections = document.querySelectorAll(".section");
const container = document.querySelector(".scroll-container");
// Navigation dengan keyboard
document.addEventListener("keydown", function (e) {
if (isScrolling) return;
if (e.key === "ArrowDown" || e.key === "PageDown") {
e.preventDefault();
scrollToNextSection();
} else if (e.key === "ArrowUp" || e.key === "PageUp") {
e.preventDefault();
scrollToPrevSection();
}
});
// Touch/Wheel events untuk scroll snap yang lebih responsif
let touchStartY = 0;
let touchEndY = 0;
container.addEventListener("touchstart", function (e) {
touchStartY = e.changedTouches[0].screenY;
});
container.addEventListener("touchend", function (e) {
if (isScrolling) return;
touchEndY = e.changedTouches[0].screenY;
handleSwipe();
});
function handleSwipe() {
const swipeThreshold = 50;
const diff = touchStartY - touchEndY;
if (Math.abs(diff) > swipeThreshold) {
if (diff > 0) {
scrollToNextSection();
} else {
scrollToPrevSection();
}
}
}
function scrollToNextSection() {
if (currentSection < sections.length - 1) {
currentSection++;
scrollToSection(currentSection);
}
}
function scrollToPrevSection() {
if (currentSection > 0) {
currentSection--;
scrollToSection(currentSection);
}
}
function scrollToSection(index) {
if (index >= 0 && index < sections.length) {
isScrolling = true;
sections[index].scrollIntoView({
behavior: "smooth",
block: "start",
});
setTimeout(() => {
isScrolling = false;
}, 800);
}
}
// Update current section berdasarkan scroll position
container.addEventListener("scroll", function () {
if (isScrolling) return;
const scrollTop = container.scrollTop;
const sectionHeight = window.innerHeight;
const newCurrentSection = Math.round(scrollTop / sectionHeight);
if (
newCurrentSection !== currentSection &&
newCurrentSection >= 0 &&
newCurrentSection < sections.length
) {
currentSection = newCurrentSection;
}
});
// API untuk navigasi programmatic
window.scrollToSection = scrollToSection;
window.getCurrentSection = () => currentSection;
});