...

View Full Version : Help with img src as id



Zwake
09-13-2011, 03:43 PM
So when the user clicks on a image in the cell of the table it is supposed to switch to another one of the images randomly. But i think i have some kind of syntax error in my x.src=newpic. Anyone see the problem? Here is the code:

<html>
<head>
<title>Untitled</title>
</head>
<script language="JavaScript" type="text/javascript">
<!--
pics=new Array()
pics[0]="picts1.gif"
pics[1]="picts2.gif"
pics[2]="picts3.gif"
pics[3]="picts4.gif"
pics[4]="picts5.gif"
pics[5]="picts6.gif"

function swappic(x){
num=Math.floor(Math.random()*6)
newpic=pics[num]
x.src=newpic
}

//if(all sources are the same)
//run function to slice image into table
//-->
</script>
<body>
<form>
<table>
<tr><td><img src="pict1.gif" id="a" onclick="swappic(this.id)"><td><img src="pict2.gif" id="b" onclick="swappic(this.id)"></tr>
<tr><td><img src="pict3.gif" id="c" onclick="swappic(this.id)"><td><img src="pict4.gif" id="d" onclick="swappic(this.id)"></tr>
</table>
</form>
</body>
</html>

Rowsdower!
09-13-2011, 03:46 PM
Instead of this:

onclick="swappic(this.id)"

Use this:

onclick="swappic(this)"

Otherwise your script is essentially trying to set this.id.src (which doesn't make sense) rather than this.src (which makes sense and is what you need to have the script do).

Zwake
09-13-2011, 06:24 PM
it still comes up with broken image links. maybe its not passing the cell id to the function? x has to be the id not the src.

Rowsdower!
09-13-2011, 06:35 PM
No, according to the function you have posted "x" needs to be an element (not an ID of an element, but the element itself - the HTML object which is the image element).

Check your array of image sources and see if you have named them correctly. I see a difference between the images in the array and the images in the existing HTML. In the array the images are named "picts1.gif, picts2.gif,..." while in the regular HTML part of the page they are named "pict1.gif, pict2.gif,..."

Does the "s" belong there in the image sources in array or not?

Zwake
09-13-2011, 06:56 PM
wow your right haha. i cant believe i overlooked that. it works now, thank you for your help!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum