Skip to content

Rotating Banner with JavaScript

Learn how to build a rotating banner with JavaScript: images that change every few seconds and link to different pages. Includes a downloadable example.

Ricardo Moya

In this tutorial we are going to build a “rotating” banner with JavaScript. By “rotating banner” we mean that we will have several banners placed in the same position that change every “x” seconds, and clicking each banner takes you to a different web page.

In this example, each banner image will be the image of one of the sections of the www.jarroba.com website, and clicking on each one will take you to the corresponding page for that section. You can download the example from DOWNLOAD THE EXAMPLE HERE.

The first thing we need to do is create two files: one will be the “html” file (the web page itself) and the other a “javascript” file. You could do everything inside the same “html” file, but as a tip, it is more convenient and tidy to keep two separate files, especially when working with complex web pages with many functions, whether JavaScript, PHP, AJAX, etc.

The first thing we need to do in the JavaScript file, which we have named “funcionesJS.js”, is create two arrays of the same size. In one of them we will store the images and in the other the URLs associated with each image. Here is what the arrays would look like.


/* ARRAY OF IMAGES */
ads = new Array(9);
ads[0] = "https://jarroba.com/wp-content/uploads/2012/03/Modelado.png";
ads[1] = "https://jarroba.com/wp-content/uploads/2012/03/LenguajesProgramacion.png";
ads[2] = "https://jarroba.com/wp-content/uploads/2012/03/AplicacionesMoviles.png";
ads[3] = "https://jarroba.com/wp-content/uploads/2012/03/TecnologiaWeb.png";
ads[4] = "https://jarroba.com/wp-content/uploads/2012/03/Servidores.png";
ads[5] = "https://jarroba.com/wp-content/uploads/2012/03/SistemasOperativos.png";
ads[6] = "https://jarroba.com/wp-content/uploads/2012/03/BaseDeDatos.png";
ads[7] = "https://jarroba.com/wp-content/uploads/2012/03/Hadware.png";
ads[8] = "https://jarroba.com/wp-content/uploads/2012/03/InteligenciaArtificial.png";

/* ARRAY OF URLs */
arrayURLs = new Array(9);
arrayURLs[0] = "https://jarroba.com/indice-ingenieria-del-software/"
arrayURLs[1] = "https://jarroba.com/lenguajes-de-programacion/"
arrayURLs[2] = "https://jarroba.com/aplicaciones-moviles/"
arrayURLs[3] = "https://jarroba.com/tecnologias-web/"
arrayURLs[4] = "https://jarroba.com/redes/"
arrayURLs[5] = "https://jarroba.com/sistemas-operativos/"
arrayURLs[6] = "https://jarroba.com/bases-de-datos/"
arrayURLs[7] = "https://jarroba.com/diseno-hardware/"
arrayURLs[8] = "https://jarroba.com/inteligencia-artificial/"

Next we need to (and this is up to you) declare a “contador” (counter) variable to walk through the array positions, and another variable to set how long the banners stay visible (the time is set in milliseconds, which is why it is multiplied by 1000).


//variable to keep track of the images
var longuitudArray = ads.length;
var contador = 0

// We pick a random number
contador = Math.floor((Math.random() * longuitudArray))

// Change the image every second in this example
var tiempo = 1// In seconds
var timer = tiempo * 1000;

Here we picked a random number between 0 and 9 “contador = Math.floor((Math.random() * longuitudArray))” (9 being the length of our array) so that when the page loads it starts with any one of our banners. If you want it to always start from the beginning, you can remove this statement and the “longuitudArray” variable.

Now we need to create two functions that change the banner image every “x” seconds. The first function (function banner()) will change the image src named banner (document.banner.src = ads[contador];) every second. What this function does is walk through the array of images with the index contador, assigning that array position to the image’s src. This function will be called every “x” seconds, which in our case is every second, set by the variable ‘timer’ in the call to the function “setTimeout("banner()", timer)”.


function banner() {
	contador++;
	contador = contador % longuitudArray
	document.banner.src = ads[contador];
	setTimeout("banner()", timer);
}

The other function (function ponerURL()) will assign to the href we specify in the “html” the URL found at each position of the URL array. In this case it will assign the URL from the URL array at the index ‘contador2’, which will have the same value as the index ‘contador’ that walks through the array of images.


function ponerURL() {
	contador2 = contador;
	url = window.open(arrayURLs[contador2]);
	return false;
}

Once we have our JavaScript functions, let’s call them from our “html” file. The first thing we need to do is import our JavaScript file named “funcionesJS.js” (we put this in the "head").


<script type="text/javascript" src="funcionesJS.js"></script>

Next we need to tell the page to run the “banner()” function when it loads. We do this by calling the function in the “body” tag, like this:


<body onload="banner()">

Next we need to assign the URL from the URL array to the corresponding ‘href’, which we do like this (target="_black" makes the page open in another tab):


<a href="javascript:ponerURL()" target="_blank">

And finally, we need to say which image element will have its images changed to form the banner, which we do like this:


<img src="" name="banner" >

In summary, this is the content of the two files created to get a rotating banner:

“funcionesJS.js”:


/* ARRAY OF IMAGES */
ads = new Array(9);
ads[0] = "https://jarroba.com/wp-content/uploads/2012/03/Modelado.png";
ads[1] = "https://jarroba.com/wp-content/uploads/2012/03/LenguajesProgramacion.png";
ads[2] = "https://jarroba.com/wp-content/uploads/2012/03/AplicacionesMoviles.png";
ads[3] = "https://jarroba.com/wp-content/uploads/2012/03/TecnologiaWeb.png";
ads[4] = "https://jarroba.com/wp-content/uploads/2012/03/Servidores.png";
ads[5] = "https://jarroba.com/wp-content/uploads/2012/03/SistemasOperativos.png";
ads[6] = "https://jarroba.com/wp-content/uploads/2012/03/BaseDeDatos.png";
ads[7] = "https://jarroba.com/wp-content/uploads/2012/03/Hadware.png";
ads[8] = "https://jarroba.com/wp-content/uploads/2012/03/InteligenciaArtificial.png";

/* ARRAY OF URLs */
arrayURLs = new Array(9);
arrayURLs[0] = "https://jarroba.com/indice-ingenieria-del-software/"
arrayURLs[1] = "https://jarroba.com/lenguajes-de-programacion/"
arrayURLs[2] = "https://jarroba.com/aplicaciones-moviles/"
arrayURLs[3] = "https://jarroba.com/tecnologias-web/"
arrayURLs[4] = "https://jarroba.com/redes/"
arrayURLs[5] = "https://jarroba.com/sistemas-operativos/"
arrayURLs[6] = "https://jarroba.com/bases-de-datos/"
arrayURLs[7] = "https://jarroba.com/diseno-hardware/"
arrayURLs[8] = "https://jarroba.com/inteligencia-artificial/"

//variable to keep track of the images
var longuitudArray = ads.length;
var contador = 0

// We pick a random number
contador = Math.floor((Math.random() * longuitudArray))

// Change the image every second in this example
var tiempo = 1// In seconds
var timer = tiempo * 1000;

function banner() {
	contador++;
	contador = contador % longuitudArray
	document.banner.src = ads[contador];
	setTimeout("banner()", timer);
}

function ponerURL() {
	contador2 = contador;
	url = window.open(arrayURLs[contador2]);
	return false;
}

“bannerRotatorio.html”:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-15">
		<script type="text/javascript" src="funcionesJS.js"></script>
		<title>Banners rotatorio Javascript</title>

	</head>

	<body onload="banner()">

		<a href="javascript:ponerURL()" target="_blank">
			<img src="" name="banner" >
		</a>

	</body>
</html>

“Rotating Banner with JavaScript” by Ricardo Moya at jarroba.com, licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0. Registered at Safe Creative.

Ricardo Moya

I work in Machine Learning and Big Data. I like learning new technologies and explaining them as clearly as I can on this site.

You may also like

LAMP Step by Step on Your Own Server

Learn step by step how to build a dynamic website with the full LAMP architecture: Linux, Apache, MySQL or MariaDB, and PHP, Perl or Python.

Sep 30, 2019

Using Servers and Building a Website

Learn what you can do with a physical server: install Apache, build your first website, edit it with Vim or an IDE, upload files over SFTP and pick a domain.

Sep 3, 2019

Comments

Leave a comment


This site uses Akismet to reduce spam. Learn how your comment data is processed.