Introduction
Configure Our Script
Getting Into the Code
To start, let's make the script configurable so it can be somewhat customized for each page on which it is embedded. The actual tracking of how far the page has been scrolled involves a program cycle. This means that the program loops through, over and over, to check whether the scrolled position of the page has changed. So, let's allow for a configurable amount of time the program should wait after it finishes one cycle, before it jumps into the next. We will use milliseconds as the unit of measurement:
// Set to amount of milliseconds to wait between vertical-scroll-distance checks
var cycleLength = 100;
Next, let's allow for the person installing the script to tell the script where to report the data upon completing. This should be in URL format and should point to the server side script that you have written to handle the incoming data.
// Set to the URL of the server-side script that handles the scroll-reports
var URLtoScript = "http://www.yoursite.com/scroll_report.php";
Now, name the variable that will hold the data during transmission to the server side script. Using the example of "reportedScrollMax", if we are using PHP on the server we would access this data on our server side script like: $_GET['reportedScrollMax'].
// Set to the name of the variable to which holds the data when sending to server
var sendVar = "reportedScrollMax";
That is all that should really be configurable in this script. Next, two variables that need to be globally accessible must be declared. The first variable we will call "clocking", and will be used in controlling the cycle of program loops. It does not need to be initialized yet. The second will be the variable that holds the maximum number of pixels that the page has been scrolled down. We will call it "scrollMax" and will initialize it by setting it to zero (0) to begin the program.
var clocking; var scrollMax = 0;
Now let's begin building the functions that will be called throughout this program's execution.
Download the JavaScript Scroll Monitor
Jim Auldridge is an active member of the Christian-web-masters.com forums. You can find him regularly helping people with their programming questions.