'how to scrollto without animation

So I use the excellent plugin from lions-mark that allows scrolling to any position a breeze. I use this mainly to keep the user at his current scroll location when the page refreshes (don't ask, mine is a legacy gaming site with auto-refresh in some instances)

So I store current scroll position into localstorage on window.onBeforeUnload and use that value to scroll to previous location after pageload.

$('content-grid').scrollTo(offsetBeforeReload);

This works, however I want to "jump" to that position without the animated scroll. I do not want to use anchors, since I already have this scrollTo code that works just fine, all I want to do is get rid of the scrollTo animation and made it look as if the page is 'anchored' to that location.

Any suggestions/solutions are very much appreciated!



Solution 1:[1]

the way i was able achieve this (in my case: to suppress scrolling animation to top while transitioning to a new view via Vue Router:

  mounted() {
    document.documentElement.style.scrollBehavior = 'auto';
    setTimeout(() => window.scrollTo(0, 0), 5);
    setTimeout(() => document.documentElement.style.scrollBehavior = 'smooth', 5);
  }

this allows you to change the style property of the html node...switching from scroll to auto to stop it and then back to scroll once scrolling is done. the setTimeout() is actually important otherwise the switch to auto won't actually take into effect.

note that this works even when you have set html set initially to smooth scrolling in your css:

html {
    scroll-behavior: smooth;
}

i tried this on Chrome and Firefox on MacOS (Big Sur) and they seem to work (smooth scrolling is not supported in Safari and Vivaldi as of this writing).

this should also work without having to use Vue.js.

Solution 2:[2]

Just use window.scrollTo. This will jump directly to the position with no animations.

var xPosition = 0;
var yPosition = 1000;
window.scrollTo(xPosition, yPosition);

Solution 3:[3]

You can set the duration option to 0 which should scroll to the element instantaneously.

$('content-grid').scrollTo(offsetBeforeReload, {duration:0});

Here is the demo from the lions-mark website updated to use a zero duration: JSFiddle

Solution 4:[4]

Here's what I needed:

window.scrollTo({ top:50, left:0, behavior: "instant"})

Solution 5:[5]

Use document.getElementByID('your-element').scrollIntoView({behavior: "instant"});

Works like a charm!

Solution 6:[6]

window.scrollTo(xPosition, yPosition) works natively in all major browsers.

If you want to use jQuery, try the following:

$('body,html').animate({ scrollTop: 0, }, 0);

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 Dexter Legaspi
Solution 2 Mike Cluck
Solution 3
Solution 4 Jesus is Lord
Solution 5 Steve Alereza
Solution 6 4b0