Rafał
Rafał

Reputation: 118

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.

Upvotes: 2

Views: 8619

Answers (3)

Juri
Juri

Reputation: 1741

I don't know why, but i had problems with { behavior: 'smooth' }

Call just scrollIntoView()

Upvotes: 5

Gigarthan
Gigarthan

Reputation: 247

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

Upvotes: 0

Adam Shone
Adam Shone

Reputation: 393

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.

Upvotes: 0

Related Questions