Saturday, February 12, 2011

JavaScript: Automated Page Switching

So, one day I got stuck at work. My boss told me to give his SharePoint site a new little feature. He called it "screen saver". At first I thought he was kidding, I told him to use the ones which come with Windows. But he meant that he needs a little "tool" that will automatically switch through his pages after a couple of minutes.

In the end I came up with a little idea, which indeed worked pretty well.

Here is the code, I will explain it below:
<html>
  <head>
    <script language="javascript" type="text/javascript">
      var addresses = new Array();
      /* fill array */
      var startt = 100000;
      var activ = window.setTimeout("Show()", startt);
      var length = 4;
      function SetTimer()
      {
        try
        {
          window.clearTimeout(activ);
          activ = window.setTimeout("Show()", startt);
        }
        catch(e)
        {
          window.status = "Error: " + e.number + "; " + e.description ;
        }
      };
      function Show()
      {
        var i = Math.floor(Math.random()*length);
        document.location = addresses[i];
      };
    </script>
  
  </head>
  <body onload="SetTimer()">
  </body>
</html>
What's happening there?

<body onload="SetTimer()">
This one is simple: start the function called "Set Timer" when the page is loaded.
 Here's the function we will call:
function SetTimer()
      {
        try
        {
          window.clearTimeout(activ);
          activ = window.setTimeout("Show()", startt);
        }
        catch(e)
        {
          window.status = "Error: " + e.number + "; " + e.description ;
        }
      };
The last part is obvious: display every error in the window status bar.
So, just let us take a look the main part. Just to make sure, that no other timer is set, I let my variable "activ" get cleared by the function "clearTimeout".
The next part is about "how to restart the counter?". Here I am using the function "setTimeout", which needs a function and specified number of milliseconds to work. After the time runs out, the function will call "Show()".
And this will do the trick: within "Show()" I am switching the pages, finally.

To keep it simple, I'm just allowing 4 items in the array "addresses". The first step is to get a random number. For that, I'm using "Math.floor(Math.random()*length)". "Floor" rounds a number downwards to the nearest integer, which is needed for the array. "Random" will provide a number between 0 and 1. To get a number between 1 and 4 I have to multiply the result of "random" with the length of my array, which is 4.

Now we got our random number "i". But what to do with it?
Set a new address in the address bar with "document.location = addresses[i];". The second part will pick the address from the array, the first part with write this part in the address bar.

Now we are done. The pages will automatically switch every couple of minutes.

No comments:

Post a Comment