Posted By

adrianparr on 12/20/12


Tagged

scroll scrollbar height position percent V percentage html5 scrolltop


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

swapnilgg
erikgeerling


HTML5 Scrollbar Percentage Position using JavaScript


 / Published in: HTML
 

This JavaScript gets you the percentage position of the browser's scrollbar.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.  
  4. <head>
  5. <meta charset="utf-8">
  6. <title>Get Scrollbar Percentage</title>
  7.  
  8. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  9.  
  10.  
  11.  
  12. $(document).ready(function() {
  13.  
  14. $(window).scroll(function(e){
  15. var scrollTop = $(window).scrollTop();
  16. var docHeight = $(document).height();
  17. var winHeight = $(window).height();
  18. var scrollPercent = (scrollTop) / (docHeight - winHeight);
  19. var scrollPercentRounded = Math.round(scrollPercent*100)/100;
  20.  
  21. $('#scrollPercentLabel>span').html(scrollPercentRounded);
  22. repositionLabel();
  23. });
  24.  
  25. $(window).resize(function(){
  26. repositionLabel();
  27. });
  28.  
  29. function repositionLabel() {
  30. $('#scrollPercentLabel').css({
  31. position:'fixed',
  32. left: ($(window).width() - $('#scrollPercentLabel').outerWidth()) / 2,
  33. top: (($(window).height() - $('#scrollPercentLabel').outerHeight()) / 2) - $('#scrollPercentLabel').height()
  34. });
  35. }
  36.  
  37. repositionLabel();
  38.  
  39. });
  40.  
  41. </script>
  42.  
  43.  
  44. body {
  45. background-image: url('http://subtlepatterns.com/patterns/crissXcross.png');
  46. margin: 0px;
  47. padding: 0px;
  48. }
  49.  
  50. #fakeHeight {
  51. height: 6000px;
  52. width: 1px;
  53. }
  54.  
  55. #scrollPercentLabel {
  56. font-family: Impact;
  57. font-size: 50px;
  58. color: #2B2B2B;
  59. background: rgba(255, 255, 255, 0.5);
  60. padding: 20px;
  61. position: absolute;
  62. top: 50%;
  63. left: 50%;
  64. box-shadow: 8px 8px 5px rgba(20, 20, 20, 1);
  65. border-radius: 15px;
  66. }
  67.  
  68. </style>
  69.  
  70. </head>
  71.  
  72. <body>
  73. <p id="fakeHeight"></p>
  74. <p id="scrollPercentLabel">scrollPercent: <span>0</span></p>
  75. </body>
  76.  
  77. </html>

Report this snippet  

You need to login to post a comment.