PDA

View Full Version : GetElementByID



kriscons
11-24-2005, 12:39 PM
Hi all,

Very new to this...

I have a div which contains an image by default when the page loads. When a user clicks a link, I need the image to change to correspond with the link.

My code is this:

<div id=imagecontainer">my image is here</div>

My LInks are:

Red
Black
Blue etc

And when the user clicks the links, the DIV changes its image to match that of the colour they clicked. I store all the paths to images in my php script, so I can sort all that out myself, its just the changing of the div code that i have no idea about.

Any advice would be gratefully received.

K.

Twey
11-24-2005, 04:20 PM
Ideally, we'd just give the image an ID, and reference its src by that. However, as it stands...

<script type="text/javascript">
function imageChange(div, path) {
var m = document.images;
// Iterate through m, checking the parent of every image and seeing if it matches div.
// If so, change its src to path.
for(var i=0;;i++)
if(m[i].parentNode === div)
m[i].src = path;
}
</script>
<a href="javascript:void(0);" onclick="imageChange(document.getElementById('imagecontainer'), 'red.jpg')">Red</a>

mwinter
11-24-2005, 05:55 PM
<a href="javascript:void(0);" [...]I know it's just an example, Twey, but please don't ever demonstrate use of the javascript: pseudo-scheme. The sooner people forget that it exists in this context, the better.

Mike