Search code examples
javascriptjs-scrollintoview

Javascript scrollIntoView() middle alignment?


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?


Solution

  • 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 );