Javascript scrollIntoView() middle alignment?
Javascript .scrollIntoView(boolean)
provide only two alignment option.
- top
- bottom
What if I want to scroll the view such that. I want to bring particular element somewhere in middle of the page?
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.
Use window.scrollTo()
for this. Get the top of the element you want to move to, and subtract one half the window height.
Demo: http://jsfiddle.net/ThinkingStiff/MJ69d/
Element.prototype.documentOffsetTop = function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop() : 0 );
};
var top = document.getElementById( 'middle' ).documentOffsetTop() - ( window.innerHeight / 2 );
window.scrollTo( 0, top );