Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make javascript scrollIntoView smooth?

In a react app, I have a method being called to bring a particular node into view as follows.

scrollToQuestionNode(id) {         const element = document.getElementById(id);         element.scrollIntoView(false); } 

The scroll happens fine, but the scroll action is a little jerky. How can I make it smooth? I don't see any options which I can give to scrollIntoView for the same.

like image 737
Sahil Sharma Avatar asked Feb 28 '17 08:02

Sahil Sharma


People also ask

How does smooth scrolling work?

If you press the mouse scroll wheel, you can move your mouse up/down and the scroll will be very smooth. Enabling a smooth scroll allows you to scroll like that with your regular wheel scroll. Smooth scrolling is also useful with keyboard shortcuts.

Can I use scrollIntoView?

scrollIntoView on Android Browser is fully supported on 97-103, partially supported on 2.3-4, and not supported on below 2.3 Android Browser versions. scrollIntoView on Opera Mobile is fully supported on 64-64, partially supported on 10-12, and not supported on below 10 Opera Mobile versions.

What is JavaScript scrollIntoView?

The scrollIntoView() method scrolls an element into the visible area of the browser window.

How do you scroll up in JavaScript?

The scrollTo() method of the window Interface can be used to scroll to a specified location on the page. It accepts 2 parameters the x and y coordinate of the page to scroll to. Passing both the parameters as 0 will scroll the page to the topmost and leftmost point.


1 Answers

This might help.

From MDN documentation of scrollIntoView You can pass in option instead of boolean.

scrollIntoViewOptions Optional A Boolean or an object with the following options: {   behavior: "auto"  | "instant" | "smooth",   block:    "start" | "center" | "end" | "nearest",   inline:    "start" | "center" | "end" | "nearest", } 

So you can simply pass parameter like this.

scrollToQuestionNode(id) {   const element = document.getElementById(id);   element.scrollIntoView({ block: 'end',  behavior: 'smooth' }); } 

Reference: https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

like image 173
lavish Avatar answered Sep 17 '22 13:09

lavish