Steve
Steve

Reputation: 61

How to scroll to middle (50%) of page

Without using the popular scrollTo plugin, how can I scroll to the vertical middle (50%) of the page/div?

Upvotes: 4

Views: 28692

Answers (2)

jaheraho
jaheraho

Reputation: 550

JQuery - jump to vert/hori middle of scroll-div

vertical

$("#centralize-ver").click(function(){//centralize vertical
    var scrollableDivJ=$("#scroll-div");
    scrollableDivJ.scrollTop("1000000");//scroll to max
    var scrollHeight=scrollableDivJ.prop("scrollHeight");
    var diff=(scrollHeight-scrollableDivJ.scrollTop())/2;
    var middle=scrollHeight/2-diff;
    scrollableDivJ.scrollTop(middle);
});

horizontal

$("#centralize-hor").click(function(){//centralize horizontal
    var scrollableDivJ=$("#scroll-div");
    scrollableDivJ.scrollLeft("1000000");//scroll to max
    var scrollWidth=scrollableDivJ.prop("scrollWidth");
    var diff=(scrollWidth-scrollableDivJ.scrollLeft())/2;
    var middle=scrollWidth/2-diff;
    scrollableDivJ.scrollLeft(middle);
});

Replace "#scroll-div" with your div. "body" isn't working for me.

jsfiddle

Thats the only solution that works properly for me. Actually its an 2h-try'n'error solution thats do its job pretty well. Maybe someone could explain why scrollTop is never reaching the value of prop("scrollheight") and the written calculation of diff and middle is necessary.

Upvotes: 1

Bart Vangeneugden
Bart Vangeneugden

Reputation: 3446

This scrolls the internal scroll of a div to it's vertical middle

var myDiv = $("#yourdiv");
var scrollto = myDiv.offset().top + (myDiv.height() / 2);
myDiv.animate({ scrollTop:  scrollto});

Upvotes: 4

Related Questions