ScrollIntoView() causing the whole page to move
You could use scrollTop
instead of scrollIntoView()
:
var target = document.getElementById("target");
target.parentNode.scrollTop = target.offsetTop;
jsFiddle: http://jsfiddle.net/LEqjm/
If there's more than one scrollable element that you want to scroll, you'll need to change the scrollTop
of each one individually, based on the offsetTop
s of the intervening elements. This should give you the fine-grained control to avoid the problem you're having.
EDIT: offsetTop isn't necessarily relative to the parent element - it's relative to the first positioned ancestor. If the parent element isn't positioned (relative, absolute or fixed), you may need to change the second line to:
target.parentNode.scrollTop = target.offsetTop - target.parentNode.offsetTop;
Fixed it with:
element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' })
see: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
I had this problem too, and spent many hours trying to deal with it. I hope my resolution may still help some people.
My fix ended up being:
- For Chrome: changing
.scrollIntoView()
to.scrollIntoView({block: 'nearest'})
(thanks to @jfrohn). - For Firefox: apply
overflow: -moz-hidden-unscrollable;
on the container element that shifts. - Not tested in other browsers.
var el = document.querySelector("yourElement");
window.scroll({top: el.offsetTop, behavior: 'smooth'});