'scrollIntoView not working on Chrome but perfeclty fine in Firefox
I've encoutnered a problem concerning scrollIntoView. The code I wrote works on Firefox, but not on Chrome. I'am not getting any errors or anything from console therefore I don't know what's the problem. How to run it correctly on Chrome? I would like to solve it in Vanilla JS
Here's my code -> https://codepen.io/Rafi-R/pen/PLdvjO
const body = document.querySelector('body');
const links = document.querySelectorAll(".link");
let section = 0;
const scrollDirection = e => e.wheelDelta ? e.wheelDelta : -1 * e.deltaY;
const scrollToSection = e => {
e.preventDefault();
section =
scrollDirection(e) < 0
? (section + 1 >= links.length - 1 ? section = links.length - 1 : section + 1)
: (section - 1 <= 0 ? section = 0 : section - 1);
let element = document.querySelector(links[section].getAttribute("href"));
scrollToTheView(element);
}
const scrollToTheView = el => {
el.scrollIntoView({ behavior: 'smooth' });
console.log(el, links[section].getAttribute("href"), section)
}
body.addEventListener('wheel', scrollToSection, { passive: false });
When codepen's console is open console.log() crashes scrollIntoView({behavior: 'smooth'}), thus scroll is not working.
Solution 1:[1]
You didn't say what you're expecting to happen, but your codepen seems to work fine for me. After each scroll down of the mouse wheel the next section slides into view.
This is with Chrome 73.0.3683.86 on Ubuntu.
Solution 2:[2]
Chrome doesn't accept all the options in the scrollIntoView method. I faced the similar issue and found out if you change the values of these options it seems to be working fine.
element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
Above snippet is working for me to scroll the element horizontally
Refer the browser compatibility section in the MDN for scrollIntoView
Solution 3:[3]
I don't know why, but i had problems with { behavior: 'smooth' }
Call just scrollIntoView()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Adam Shone |
| Solution 2 | Gigarthan |
| Solution 3 | Juri |
