Search code examples
javascriptscrollsmooth-scrolling

How to Instantly Scroll to Position?


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' });

Solution

  • 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>