Javascript .scrollIntoView(boolean)
provide only two alignment option.
What if I want to scroll the view such that. I want to bring particular element somewhere in middle of the page?
To use JavaScript scrollIntoView to do smooth scroll with offset, we can call scrollTo with an object that has the top and behavior properties. const element = document. getElementById("targetElement"); const headerOffset = 45; const elementPosition = element. getBoundingClientRect().
scrollIntoView(true);", element); This works for vertical scrolling but not for horizontal.
The scrollIntoView() method scrolls an element into the visible area of the browser window.
Say your page displays a list of names and you want a certain person to be highlighted and scrolled into view. There's a browser API for that: Element. scrollIntoView() , which scrolls an element into view.
try this :
document.getElementById('myID').scrollIntoView({ behavior: 'auto', block: 'center', inline: 'center' });
refer here for more information and options : https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
It is possible to use getBoundingClientRect()
to get all the information you need to achieve this. For example, you could do something like this:
const element = document.getElementById('middle'); const elementRect = element.getBoundingClientRect(); const absoluteElementTop = elementRect.top + window.pageYOffset; const middle = absoluteElementTop - (window.innerHeight / 2); window.scrollTo(0, middle);
Demo: http://jsfiddle.net/cxe73c22/
This solution is more efficient than walking up parent chain, as in the accepted answer, and doesn't involve polluting the global scope by extending prototype (generally considered bad practice in javascript).
The getBoundingClientRect()
method is supported in all modern browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With