How to detect scroll action using JavaScript

To fire up different actions in a web page when someone scroll on it we need to detect scroll events on the page.

Completed project can be Download from here.
In this tutorial color of a div(div with ID "maincontent") is changed when a user is scrolling the page,

Here is how it can be done.

  1. Add onscroll attribute in the element which you need to detect scroll on.
    ex:<body onscroll="bodyScroll();"></body>

  2. Declare a JavaScript variable to -1. (In this tutorial scrollTimer)

  3. Implement the bodyScroll() function
       function bodyScroll() {        
            $('#maincontent').css('background-color','lightGrey'); 
            
            if (scrollTimer != -1)
                clearTimeout(scrollTimer);

            scrollTimer = window.setTimeout("scrollFinished()", 300);
        }

  4. Implement the scrollFinished() method.
        function scrollFinished() {
           $('#maincontent').css("background","white");
        }

Note: In the project I have added extra reference to bootstrap  for easiness of making the UI.

This post shows hot do this using JQuery scroll() method.

Please add a comment if this was useful to you or you have something to add



No comments:

Post a Comment