I have a JavaScript function that attempts to smoothly scroll an element into view:
dom_element.scrollIntoView({
'behavior': 'smooth',
'block': 'nearest'
});
On Firefox, this works perfectly fine.
But I realized that scrolling was instant, i.e. not respecting behaviour': 'smooth'
on Chromium-based browsers (Chrome, Opera, Brave).
Both MDN and caniuse.com showed that Chrome supported behaviour: smooth
, so I was quite puzzled.
After a frustrating hour of debugging, I realized that the code works if I specifically go to chrome://flags/#smooth-scrolling
and toggle Smooth Scrolling from Default to Enabled. After some experimentation, I deduced that a value of Default for Smooth Scrolling meant Disabled.
The strange thing was: on another computer (laptop), the above code worked as expected without needing to tweak Smooth Scrolling. It was left as default, and scrolling was smooth.
Both PCs run the latest Chrome v83.0.4103.61 on Win 10 Pro.
Questions:
- Why is the default setting for the Smooth Scrolling flag different for two computers? If hardware matters, one is a desktop i7-6700K with nVidia 1060GT, and the other is a laptop i7-8550U with GeForce MX110.
- Since it's impractical to tell users to enable this flag before using the site, is it possible to override this flag programmatically in JS?
A snippet that demonstrates this problem for some PCs on Chrome:
let dom_target = document.querySelector('#target');
// Make clicks anywhere scroll smoothly to target (number 14)
document.addEventListener('click', function() {
dom_target.scrollIntoView({
'behavior': 'smooth',
'block': 'nearest'
});
});
#container {
overflow: scroll;
border: 1px solid #333;
}
.item {
border: 1px solid #333;
height: 100px;
background-color: red;
text-align: center;
color: white;
font-size: 40px;
line-height: 100px;
}
#target {
background-color: blue;
}
<h1>Clicking anywhere scrolls to 14, and the scrolling behavior should be smooth.</h1>
<section id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
<div class="item">11</div>
<div class="item">12</div>
<div class="item">13</div>
<div class="item" id="target">14</div>
<div class="item">15</div>
<div class="item">16</div>
</section>