s_bist
May 9th, 2002, 06:36 AM
How can you change the link of an image dynamically?
I have an array of images and all images should go to different links. How can u do that?
websmith99
September 30th, 2002, 05:36 PM
Have one array for the images, and another array for the link URLs.
Whatever determines the array index for the images (random number, loop, etc) will use the same index for the link URLs.
You can set this up in a JavaScript function that is called on the onClick event for the link- then set the window.location to the link URL represented by the index.
<html>
<head>
<script language="JavaScript">
myImages = new Array(3);
for (i=0; i<3; i++) {
myImages[i] = new Image();
}
myImages[0].src="cool.gif";
myImages[1].src="audio.gif";
myImages[2].src="bluearrow_left.gif";
myLinks = new Array("http://www.yahoo.com", "http://www.excite.com", "http://www.lycos.com");
random.m = 714025;
random.a = 4096;
random.c = 150889;
random.seed = (new Date()).getTime() % random.m;
function random() {
random.seed = (random.seed * random.a + random.c) % random.m;
return Math.round((random.seed / random.m) * 2);
// This will generate a random integer between 0 and 2. If you
// want to increase the range to between 0 and x, replace the
// "2" in the above line with "x"
}
function assignImage() {
document.foo.src = myImages[random()].src;
}
function doLink(){
for (i=0; i<myImages.length; i++) {
if (document.foo.src == myImages[i].src) {
theIndex = i;
}
}
window.location = myLinks[theIndex];
}
</script>
</head>
<body onLoad="assignImage()">
<a href="#" onClick="doLink(); return false"><img src="default.gif" name="foo" border="0"/></a>
</body>
</html>
:cool: