Reputation: 61
Without using the popular scrollTo plugin, how can I scroll to the vertical middle (50%) of the page/div?
Upvotes: 4
Views: 28692
Reputation: 550
$("#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);
});
$("#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.
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
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