Skip to content Skip to sidebar Skip to footer

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 mid

Solution 1:

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

Solution 2:

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.

Solution 3:

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 () {
    returnthis.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop() : 0 );
};

var top = document.getElementById( 'middle' ).documentOffsetTop() - ( window.innerHeight / 2 );
window.scrollTo( 0, top );

Solution 4:

Scrolling to the middle of an element works well if its parent element has the css: overflow: scroll;

If it's a vertical list, you can use document.getElementById("id").scrollIntoView({block: "center"}); and it will scroll your selected element to the vertical middle of the parent element.

Cheers to Gregory R. and Hakuna for their good answers.

Further Reading:

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

https://developer.mozilla.org/en-US/docs/Web/CSS/overflow

Solution 5:

document.getElementById("id").scrollIntoView({block: "center"});

Post a Comment for "Javascript Scrollintoview() Middle Alignment?"