I am using ScrollIntoView() to scroll the highlighted item in a list into view. When I scroll downwards ScrollIntoView(false) works perfectly. But when I scroll upwards, Scr
scrollintoview()
increases usabilityInstead of default DOM implementation you can use a plugin that animates movement and doesn't have any unwanted effects. Here's the simplest way of using it with defaults:
$("yourTargetLiSelector").scrollintoview();
Anyway head over to this blog post where you can read all the details and will eventually get you to GitHub source codeof the plugin.
This plugin automatically searches for the closest scrollable ancestor element and scrolls it so that selected element is inside its visible view port. If the element is already in the view port it doesn't do anything of course.
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;
var el = document.querySelector("yourElement");
window.scroll({top: el.offsetTop, behavior: 'smooth'});
Just to add an answer as per my latest experience and working on VueJs. I found below piece of code ad best, which does not impact your application in anyways.
const el = this.$el.getElementsByClassName('your_element_class')[0];
if (el) {
scrollIntoView(el,
{
block: 'nearest',
inline: 'start',
behavior: 'smooth',
boundary: document.getElementsByClassName('main_app_class')[0]
});
}
main_app_class
is the root class
your_element_class
is the element/view where you can to scroll into
And for browser which does not support ScrollIntoView() just use below library its awesome https://www.npmjs.com/package/scroll-into-view-if-needed
Play around with scrollIntoViewIfNeeded()
... make sure it's supported by the browser.
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:
.scrollIntoView()
to .scrollIntoView({block: 'nearest'})
(thanks to @jfrohn).overflow: -moz-hidden-unscrollable;
on the container element that shifts.