I was trying to make a simple full page scroll effect with the scrollIntoView
method. But it just jump to the section instantly instead of ‘smooth scrolling’ although I have already set this in the option behavior: "smooth"
.
I’m using the latest version of Edge, I have also tested on Firefox, both are not working. The reason why I test on different browser is because I have try Google relevant tutorial, weirdly their example are not working too, so I wonder is it my code is wrong or something is wrong with my browser or laptop:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_element_scrollintoview
https://www.javascripttutorial.net/javascript-dom/javascript-scrollintoview/
Watch my record: https://streamable.com/xbfh31
Below is the minimal code that you can test:
document.addEventListener("DOMContentLoaded", () => {
const sections = document.querySelectorAll(".section");
let currentSection = 0;
function scrollToSection(index) {
sections[index].scrollIntoView({ behavior: "smooth" });
currentSection = index;
}
// Mouse Wheel Event
document.addEventListener("wheel", (event) => {
if (event.deltaY > 0 && currentSection < sections.length - 1) {
scrollToSection(currentSection + 1);
} else if (event.deltaY < 0 && currentSection > 0) {
scrollToSection(currentSection - 1);
}
});
// Touch Events for Mobile Devices
let touchStartY = 0;
let touchEndY = 0;
document.addEventListener("touchstart", (event) => {
touchStartY = event.touches[0].clientY;
});
document.addEventListener("touchend", (event) => {
touchEndY = event.changedTouches[0].clientY;
const deltaY = touchEndY - touchStartY;
if (deltaY > 0 && currentSection > 0) {
scrollToSection(currentSection - 1);
} else if (deltaY < 0 && currentSection < sections.length - 1) {
scrollToSection(currentSection + 1);
}
});
});
body,
html {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
}
.section {
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
}
#section1 {
background-color: blue;
}
#section2 {
background-color: green;
}
#section3 {
background-color: gray;
}
<div id="section1" class="section">
<h2>Section 1</h2>
</div>
<div id="section2" class="section">
<h2>Section 2</h2>
</div>
<div id="section3" class="section">
<h2>Section 3</h2>
</div>