Displaying "Random" Text or Images

Suppose that you want to display one of a number of ads on your page. Maybe you just want a section of the text on your page to display one of a number of alternatives for some reason. Well you can easily achieve this effect using a javascript.

As an example of what you can do with this just look at the line of text below the site heading at the top of this page. If this is the first page that you have accessed on this site then you see a message telling you that the computer image in the top left corner of each page is a link to the home page of the site (see Welcoming Visitors to Your Site for the javascript that allows you to test for that). If this isn't the first page that you have accessed on this site then you will see one of several messages "advertising" one or more of the other pages on this site. This line then effectively forms an ad for one of the other pages on my site that I want to encourage people to visit. I can't put links to all of my pages everywhere so I have selected a few pages that I want to promote and have used this script to randomly select one of these links to display at the top of the page. This "randomly selected" link is generated by the following javascript that you can place into your page where you want the selected text or graphic to appear.

 var mess = new Array('code0','code1','code2');
var max = mess.length;
var num = Math.floor((Math.random() * max));

To see the effect of this javascript more clearly try refreshing this page. Chances are that the link below the site heading will change. This is because which of the several messages that displays is "randomly" selected at the time of displaying the page and each time the page is refreshed the code executes again.

What the code that gets inserted can be is just about anything, all you do is to assign whatever code that you want to the entries in the array. Just separate the entries that you want with commas.

In my case I used straight text with hyperlinks but you can use images just as easily by including the <img> tag with the appropriate parameters directly within the array. In the case of my code, I don't assign the text in the array definition (leaving the Array() empty) and assign the values in separate statements following the array definition so that I can assign the content of one array entry to another and manipulate the frequency at which the different messages appear (I have one entry that appears three times out of the eight alternatives).


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow