Gaffer wrote:
Hello
I want to randomize a menu which contains tables with image links
(advertisement s) inside them. I want the link image to change when refreshed
so that it's new content that a user might not have seen previously. I'm
relatively new to JS so could you please explain more about how I could do
this. Incase you don't already know, I am using .asp pages for my site.
_____
Gaffer
Heya Gaffer,
Okay. If there's not aready some simple container for the menu, wrap the
server-side include in a span or div element with a unique ID:
<div id="menu1">
<!--#include virtual "cgi-bin/menu1.txt" -->
</div>
For simplicity, we'll keep the javascript off the page in a text file
with a .js extension, such as myScript.js. The text file should have the
following content:
function randomizeMenuAd s(menuId, numOfImages) {
numOfImages++;
if(document.get ElementById(men uId)!=null) {
var myMenuImages =
document.getEle mentById(menuId ).getElementsBy TagName("img");
for(i=0;i<myMen uImages.length; i++) {
var randImageNumber = Math.floor(numO fImages*Math.ra ndom()); //
the range of random() is [0,1)
myMenuImages[i].src = "myImageDirecto ry/menuImage" +
randImageNumber .toString() + ".jpg";
}
}
}
Consecutively number your menu images and name them with the same
prefix, ie. above we have a subdirectory called "myImageDirecto ry" that
is filled with files of the form menuImage0.jpg, menuImage1.jpg, etc.
Note that the directory is relative to the location of the page the
script is run on, not the location of the javascript file. Also note
that I assumed that all the images inside the #menu1 div were randomized
images. If not, use some other HTML element to surround only the images
to be randomized within menu1.txt and set that element's "id" attribute
to "menu1" (removing the surrounding div and ID we used before). Include
the function in the head of the webpage using a script element "<script
type="text/javascript" src="myScript.j s"></script>". Next we call the
function on every page load using "<body
onload="randomi zeMenuAds('menu 1', 10)">" if the amount of images you
have is 11 since we're numbering from 0. It is also a good idea to drop
the tag "<meta http-equiv="Content-Script-Type"
content="text/javascript" />" into the head element of the page that is
going to be using intrinsic events like onload.