JavaScript Ad Rotator


I discovered recently that this site has been up and active for over a year now with no major changes. However, I have looked over my code and found that there are certain things that should be fixed and expanded. Among other things, the search engine is currently very simple since it only can search on a word or text string in the database. The changes is nothing that will affect the functionality of the page. But enough about the boring part for now is the time to share with you another piece of code that I dug up in my archives.

This code example shows a simple ad rotator written in Javascript. The script shows a link with a clickable image, which, after a few seconds is replaced with the next link with picture. It is a feature that has been around for a while on web but it is easy to modify to create other effects on your website. As it is written in Javascript, no code needs to run on a Web server, but everything is executed by the user’s browser. First, the Javascript code is presented whereupon the HTML code is displayed.

<script type="text/javascript">
//This code can be run both in the head and body.

//Global variable that stores advertising banners.
var ads = new Array();

//Function that starts when the page finished loading.
window.onload = function(){
  //Adds information about the new banners.
  ads.push(["", "valid-css.png", "CSS"]);
  ads.push(["", "valid-xhtml.png", "XHTML"]);
  ads.push(["", "valid-svg.png", "SVG"]);

  //Starting rotation with the first banner.

function ad_rotate(active){
  //Gets the div that will display banners.
  var ad_element = document.getElementById("ad");

  //Prints a new link with image in advertising box.
  ad_element.innerHTML = "<a href=\""+ads[active][0]+"\"><img src=\""+ads[active][1]+"\" alt=\""+ads[active][2]+"\" title=\""+ads[active][2]+"\" /></a>";

  //Switches to the next banner.

  //If the counter has reached the end, it shall start again from zero.
  if(active >= ads.length){
    active = 0;

  //Run the function in 5000 milliseconds (5 seconds).
  setTimeout("ad_rotate("+active+")", 5000);

Here is the HTML code used to place the advertising banner in any location on your website.

<!-- This code is placed where the advertising banner will be -->
<div id="ad"> </div>