Trying to execute js code when the user scrolls
<p>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.</p>

<p>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".</p>

<p>I tried doing this with scrollTop, scrollHeight, and clientHeight, but it doesn't seem to fire the alert on scroll.</p>

<p>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.</p>

<p>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).</p>

<p>Here is my code:</p>

<pre><code>var body = $('body');
var scrollTop = body.scrollTop;
var difference = body.scrollHeight - body.clientHeight;
var percentScrolled = (scrollTop/difference)*100;
if(percentScrolled &gt; 0){
alert("scrolled!");
}
</code></pre>

<p><strong>Update</strong>:</p>

<p>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?</p>

<p>Here is the code:</p>

<pre><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 &gt; 0){
        alert("scrolled");
    }
};
</code></pre>
