6

How to instantly scroll window to some position with JavaScript, when smooth-scrolling is enabled?

:root {
    scroll-behavior: smooth;
}

Is there a way to ignore this CSS rule? Something like this:

window.scrollBy({ top: 0, behavior: 'instantly' });
  • The only valid values for [`behavior`](https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions/behavior) are `smooth` and `auto`. There is no `instantly`. – Turnip Nov 27 '19 at 13:32
  • @Turnip oh, really? Are you kidding, don't you? I know that there is no `behavior: instantly`, I wrote it as an example. – Monsieur Pierre Doune Nov 27 '19 at 13:48
  • @Turnip ok, ok. I understand I can't do this with `scrollBy`, I'm looking for some other way to realise instant scroll. That was just an example of what I want to get. – Monsieur Pierre Doune Nov 27 '19 at 14:05

4 Answers4

12

There you go :

window.scrollTo({
  top: 0,
  left: 0,
  behavior: 'instant',
});
Lucas Demea
  • 361
  • 4
  • 8
  • 1
    Seems 'instant' doesn't exist anymore, only "auto", which is the default and supposed to be the same as "instant" (but I'm not sure it works), or "smooth" which is animated smoothly. – Dror Bar Feb 12 '23 at 15:43
  • 1
    "instant" value appears to be still valid according to [MDN docs](https://prnt.sc/uOlOMhao-Bwi) – fmuser Feb 23 '23 at 13:40
5

scroll-behavior: auto; DOES NOT work. and scroll-behavior: instant; no longer exists

This is the only thing that worked for me:

html {

  scroll-behavior: auto !important;

}
ThePrince
  • 818
  • 2
  • 12
  • 26
1

Perhaps you could set the scroll-behavior before calling .scrollBy() and then reset it after.

var root = document.querySelector(':root');
var btnInstantScroll = document.querySelector('#btnInstantScroll');
var btnDefaultScroll = document.querySelector('#btnDefaultScroll');

btnInstantScroll.addEventListener('click', function() {

  // Change scroll behavior
  root.setAttribute("style", "scroll-behavior: auto;");

  // Timeout ensures styles are applied before scrolling
  setTimeout(function() {
    window.scrollBy(0, -2000);
    
    // Reset to CSS defaults.
    root.removeAttribute("style");
  }, 0)

})

btnDefaultScroll.addEventListener('click', function() {
  window.scrollBy(0, -2000);
})
:root {
  scroll-behavior: smooth;
}

.scrollable {
  height: 2000px;
  background: repeating-linear-gradient(#e66465, #e66465 20px, #9198e5 20px, #9198e5 25px);
}

.controls {
  padding: 15px;
  position: fixed;
  bottom: 0;
}
<div class="scrollable">

</div>

<div class="controls">
  <button type="button" id="btnInstantScroll">
    Instant scroll
  </button>

  <button type="button" id="btnDefaultScroll">
    Scroll using doc settings
  </button>
</div>
Turnip
  • 35,836
  • 15
  • 89
  • 111
0

Have you tried scroll option behavior: auto?

var scrollOptions = {
    left: leftValue,
    top: topValue,
    behavior: 'auto'
}

window.scrollBy(scrollOptions);
reezvi
  • 46
  • 4