139

Javascript .scrollIntoView(boolean) provide only two alignment option.

  1. top
  2. bottom

What if I want to scroll the view such that. I want to bring particular element somewhere in middle of the page?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dhruv
  • 10,291
  • 18
  • 77
  • 126

10 Answers10

210

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

hakuna
  • 6,243
  • 10
  • 52
  • 77
  • 11
    in combination with the polyfill, this is the best answer. https://www.npmjs.com/package/smoothscroll-polyfill – ryanrain Jul 02 '18 at 22:08
  • 5
    Only Chrome and Opera fully support block and inline, not even the smoothscroll polyfill does. It's the solution we want, but sadly not the one that works. – dube Aug 27 '18 at 14:51
  • I am using the same solution in my project on IE11, Firefox, Chrome and Safari with Angular 5. – hakuna Aug 27 '18 at 16:51
  • 2
    @Sri7 Safari, IE and Edge do not understand the object-option of `scrollIntoView` and do whatever they want. Even on latest versions; I just tested it again. – dube Aug 28 '18 at 07:11
  • I can confirm this does not work on mobile safari as of today. window.scrollBy works. – Fabian von Ellerts Jan 07 '19 at 16:51
  • there is also a `scrollIntoViewIfNeeded(true)` if your browser supports https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoViewIfNeeded – alphakevin Jun 28 '19 at 02:55
  • This is the best solution for Chrome – justin Jun 23 '20 at 00:02
  • @ryanrain The smoothscroll-polyfill package seems abandoned and does not support `block` and `inline` parameters. Use this instead: https://www.npmjs.com/package/seamless-scroll-polyfill – Daniel Nov 17 '20 at 12:25
  • Working in an Angular component... With inline: 'center' the right-hand side moved inward, messing everything up, but inline: 'end' fixed that and now it's centering with block: 'center'. – Gabriel Kunkel Sep 04 '21 at 20:53
  • 2022. as of today. it works on Safari on desktop. – Jin Lim Sep 07 '22 at 17:03
88

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 browsers.

danronmoon
  • 3,814
  • 5
  • 34
  • 56
Rohan Orton
  • 1,202
  • 12
  • 14
  • Sadly, this breaks with absolute positioned elements. – dube Aug 28 '18 at 07:07
  • Can you edit your answer to include how to do it when the element is in a scrollable container instead of the page? I tried: https://jsfiddle.net/qwxvts4u/1/ – JBis Nov 19 '19 at 22:41
  • Solved with the help of [@KevinB](https://stackoverflow.com/users/400654/kevin-b) https://jsfiddle.net/5ce062tn/ – JBis Nov 19 '19 at 23:45
  • This solution worked for me *with fixed header* – Dev05 Mar 17 '21 at 13:18
55

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 );
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
20
document.getElementById("id").scrollIntoView({block: "center"});
Gregory R.
  • 1,815
  • 1
  • 20
  • 32
15

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

Matt Wyndham
  • 371
  • 3
  • 6
9

You can do it in two steps :

myElement.scrollIntoView(true);
var viewportH = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
window.scrollBy(0, -viewportH/2); // Adjust scrolling with a negative value here

You can add the height of the element if you want to center it globaly, and not center its top :

myElement.scrollIntoView(true);
var viewportH = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
window.scrollBy(0, (myElement.getBoundingClientRect().height-viewportH)/2);
fred727
  • 2,644
  • 1
  • 20
  • 16
  • 2
    this is the best answer for year 2018. first use normal "scrollIntoView", because "center" option is broken in Firefox 36 to 58 , and options are not supported by IE, see this https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView#Browser_compatibility . then you can center the scroll by calculate half of the viewport and move the scroll there. – crisc2000 Sep 15 '18 at 11:47
3

With JQuery I use this:

function scrollToMiddle(id) {

    var elem_position = $(id).offset().top;
    var window_height = $(window).height();
    var y = elem_position - window_height/2;

    window.scrollTo(0,y);

}

Example:

<div id="elemento1">Contenido</div>

<script>
    scrollToMiddle("#elemento1");
</script>
SergiP
  • 106
  • 5
2

Improving the answer of @Rohan Orton to work for vertical and horizontal scroll.

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.

var ele = $x("//a[.='Ask Question']");
console.log( ele );

scrollIntoView( ele[0] );

function scrollIntoView( element ) {
    var innerHeight_Half = (window.innerHeight >> 1); // Int value
                        // = (window.innerHeight / 2); // Float value
    console.log('innerHeight_Half : '+ innerHeight_Half);

    var elementRect = element.getBoundingClientRect();

    window.scrollBy( (elementRect.left >> 1), elementRect.top - innerHeight_Half);
}

Using Bitwise operator right shift to get int value after dividing.

console.log( 25 / 2 ); // 12.5
console.log( 25 >> 1 ); // 12
Yash
  • 9,250
  • 2
  • 69
  • 74
2

None of the solutions on this page work when a container other than the window/document is scrolled. The getBoundingClientRect approach fails with absolute positioned elements.

In that case we need to determine the scrollable parent first and scroll it instead of the window. Here is a solution that works in all current browser versions and should even work with IE8 and friends. The trick is to scroll the element to the top of the container, so that we know exactly where it is, and then subtract half of the screen's height.

function getScrollParent(element, includeHidden, documentObj) {
    let style = getComputedStyle(element);
    const excludeStaticParent = style.position === 'absolute';
    const overflowRegex = includeHidden ? /(auto|scroll|hidden)/ : /(auto|scroll)/;

    if (style.position === 'fixed') {
        return documentObj.body;
    }
    let parent = element.parentElement;
    while (parent) {
        style = getComputedStyle(parent);
        if (excludeStaticParent && style.position === 'static') {
            continue;
        }
        if (overflowRegex.test(style.overflow + style.overflowY + style.overflowX)) {
            return parent;
        }
        parent = parent.parentElement;
    }

    return documentObj.body;
}

function scrollIntoViewCentered(element, windowObj = window, documentObj = document) {
    const parentElement = getScrollParent(element, false, documentObj);
    const viewportHeight = windowObj.innerHeight || 0;

    element.scrollIntoView(true);
    parentElement.scrollTop = parentElement.scrollTop - viewportHeight / 2;

    // some browsers (like FireFox) sometimes bounce back after scrolling
    // re-apply before the user notices.
    window.setTimeout(() => {
        element.scrollIntoView(true);
        parentElement.scrollTop = parentElement.scrollTop - viewportHeight / 2;
    }, 0);
}
danronmoon
  • 3,814
  • 5
  • 34
  • 56
dube
  • 4,898
  • 2
  • 23
  • 41
1

To support all options in scrollIntoViewOptions for all browsers it's better to use seamless-scroll-polyfill (https://www.npmjs.com/package/seamless-scroll-polyfill)

Worked for me.

Here is a link with explanation https://github.com/Financial-Times/polyfill-library/issues/657

Julia
  • 674
  • 1
  • 6
  • 18