JQuery - jump in vert / hori in the middle of a 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. The "body" does not work for me.
jsfiddle
This is the only solution that works correctly for me. In fact, his 2h-try'n'error solution does its job very well. Perhaps someone can explain why scrollTop never reaches the value of prop ("scrollheight"), and a written calculation of diff and middle is needed.
source share