How to scroll to the middle (50%) of a page

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

+4
source share
3 answers

This scrolls the inner scroll div to it vertically.

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

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.

+1
source
 function scroll(div, px){ $(div).animate({scrollTop:$(div).scrollTop()+px}, 400); } scroll('body', $('body').innerheight()); 
-1
source

All Articles