How can I find out what percentage of the vertical scrollbar a user has moved through at any given point?
It's easy enough to trap the onscroll
event to fire when the user scrolls down the page, but how do I find out within that event how far they have scrolled? In this case, the percentage particularly is what's important. I'm not particularly worried about a solution for IE6.
Do any of the major frameworks (Dojo, jQuery, Prototype, Mootools) expose this in a simple cross-browser compatible way?
The scrollTop() method sets or returns the vertical scrollbar position for the selected elements.
To detect if a user is scrolling with JavaScript, we can watch for scroll events by adding event handlers. to add the userHasScrolled variable. Then we set the window. onscroll property to a function that runs when we scroll.
To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.
Oct 2016: Fixed. Parentheses in jsbin demo were missing from answer. Oops.
var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight'; var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
function getScrollPercent() { var h = document.documentElement, b = document.body, st = 'scrollTop', sh = 'scrollHeight'; return (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100; }
jQuery
(original answer):$(window).on('scroll', function(){ var s = $(window).scrollTop(), d = $(document).height(), c = $(window).height(); var scrollPercent = (s / (d - c)) * 100; console.clear(); console.log(scrollPercent); })
html{ height:100%; } body{ height:300%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With