user2039981
user2039981

Reputation:

JavaScript - Scroll down to element

You can scroll to an element using a url with a hashtag and the elements ID:

window.location.href = "#ID"

This will scrol so that the top of the element is at the top of the browser. How would I scroll to an element so that it's vertically centered?

Upvotes: 1

Views: 423

Answers (3)

user2039981
user2039981

Reputation:

This is what I have achieved:

function centerScroll(element) {
    if (!(element instanceof Element)) {
        throw new TypeError("Element expected");
    }

    var bodyRect = document.body.getBoundingClientRect();
    var elementRect = element.getBoundingClientRect();

    var left = elementRect.left - bodyRect.left;
    var top = elementRect.top - bodyRect.top;

    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;

    var elementWidth = element.offsetWidth;
    var elementHeight = element.offsetHeight;

    var x = left - Math.max(0, (windowWidth - elementWidth) / 2);
    var y = top - Math.max(0, (windowHeight - elementHeight) / 2);

    window.scrollTo(x, y);

    return [x, y];
}

Upvotes: 1

user663031
user663031

Reputation:

No, there's no built-in way, you'd have to write that yourself:

function center_element_vertically(elt) {
    var rect = elt.getBoundingClientRect();
    window.scrollTo(0, rect.top + window.pageYOffset - 
        (window.innerHeight - rect.height)/2);
}

Alternatives without writing your own code: you could scroll so that the element was at the bottom by passing false to scrollIntoView, or scroll only if the element is not already visible by calling scrollIntoViewIfNeeded, available only in Chrome AFAIK.

Upvotes: 0

dandavis
dandavis

Reputation: 16726

you can scroll up right after the navigation happens:

addEventListener("hashchange", function(){
    setTimeout(function(){ 
          document[
             document.documentElement.scrollTop ? 
             "documentElement":
             "body"
          ].scrollTop-= (innerHeight/2.1);
     }, 1); 
}, false);

this will cause the focused element to appear half-way up the screen, vertically centered. the 2.1 causes it to scroll just under half the screen, since there will be some room at the top already. you can adjust the ".1" to match your desired effect (baseline, middle, etc).

obligatory fiddle link: http://jsfiddle.net/ckhafLzq/2/

Upvotes: 1

Related Questions