I am trying to execute some js code, right now they are replaced by alerts, when the scroll-bar has moved from the top to any other height.
So when the user scrolls for the first-time, the alert "scrolled" will fire. and if the user scrolls back to the top, it resets and fires an alert "back at top".
I tried doing this with scrollTop, scrollHeight, and clientHeight, but it doesn't seem to fire the alert on scroll.
I'm not trying to fire the alert everytime the user scrolls, just on the first scroll. But it resets and a new alert is fired if the user scrolls-back to the top.
So if they scroll from top to X, alert "scrolled" fires. If they scroll from X to Y, nothing happens. If the scroll from X or Y to top, "back at top" fires. And then if the scroll from top to X or Y, it has reset and the alert "scrolled" fires (again).
Here is my code:
var body = $('body');
var scrollTop = body.scrollTop;
var difference = body.scrollHeight - body.clientHeight;
var percentScrolled = (scrollTop/difference)*100;
if(percentScrolled > 0){
alert("scrolled!");
}
Update:
I now have this working thanks to one of the comments, it fires the "back to top" alert when scrolled back to the top, but fires the alert "scrolled" on every scroll. How can I get the "scrolled" alert to fire only when the scroll-bar moves from the top to any other location besides the top?
Here is the code:
window.onscroll = function () {
var doc = document.body,
scrollPosition = doc.scrollTop,
pageSize = (doc.scrollHeight - doc.clientHeight),
percentageScrolled = Math.floor((scrollPosition / pageSize) * 100);
if(percentageScrolled == 0){
alert("back at top");
}
else if(percentageScrolled > 0){
alert("scrolled");
}
};