Random Banner Tutorial

 

In this tutorial I will give you the code for making a random banner (or any image) showing up on your page every time it’s refreshed or opened.

I’ll first give you the code and then I will explain how it works and what you can or need to change.

You have to make a file with the javascript code in it that you will use.
You can make this file in any webeditor: Notepad, Dreamweaver… Just make sure you save the file as banner.js. The suffix .js stands for javascript.

In this file you’ll put the following code:

var number = (Math.ceil(Math.random()*5));
document.write('<img src="img/banner'+number+'.jpg">');

In the html file where you want the banner to show up, you need to load the banner.js file. You’ll do this by putting the following code in.

<script src="banner.js"></script>

You can put this line of code anywhere in your html file. You just put it where you need it. If you want a banner on top, this line of code will be the first line after the <body> tag. If you want it at the bottom of your page it will be the last line of code before </body>.

Now, for the code in the .js file. The only thing you can change in the code, is the text in blue. Leave the rest the way it is, or it won’t work. This example assumes that you have made 5 banners with the names banner1.jpg, banner2.jpg, banner3.jpg, banner4.jpg and banner5.jpg.

You need to make sure that all your banners or images have the same name and that there’s only a difference in the number at the end.

You can use more banners for this, but then you have to change the number 5 to the number of banners that you have.

Math.ceil(Math.random()*5)

This function will create a number between 1 and 5. Math.random returns a random number between 0,1 and 0,9. This will be multiplied by 5 (or any other number you put in). Math.ceil will round up the number to a non-decimal number.

document.write will write the right html code into your html page. If the number created by the function is 2 the following code will be written in your html page.

<img src="img/banner2.jpg">

Then this is left.

img/banner

You need to put in a source, where the webpage can find the banners it needs. img is the folder in which you put all the banners. You don’t have to put them in a separate folder, but I think it’s easier. And banner is the name of all your image files. They should all have the same name, except for the number. The number will be randomly created by the .js file, so that every time the page is refreshed another banner will pop up.

You have to make sure though that banner.js, yourwebpage.html and the img folder are all in the same folder. Otherwise the links won’t work.

If you have any questions or problems, just send an email to the following address ses_gatergirl@yahoo.com.
Good luck!

*ses*

back to top