...

View Full Version : my code stops looping



esotericsean
10-14-2006, 05:26 AM
I'm trying to write a little script that allows you to click on an image and then the image is replaced with a new one. However, the code I've written works for one click but then stops for some reason.

I'm new to javascript, so maybe I'm just missing something, but I'd really appreciate all the help I can get. Thanks :)


<html>

<head>
<script>
var amount = 5;
var mainImages = new Array();

for (i = 0; i < amount; i++)
{
mainImages[i] = "images/portrait" + i + ".jpg";
}

function nextImage(p)
{
if (p <= amount)
p++;
else
p = 0;

document.write ('<img src="' + mainImages[p] + '" onClick="nextImage(' + p + ')">');
}
</script>
</head>

<body>
<script>
var p = 1;
document.write ('<img src="images/portrait' + p + '.jpg" onClick="nextImage(' + p + ')">');
</script>
</body>

</html>

Kravvitz
10-14-2006, 06:07 AM
document.write() can only be used while the page is loading -- if it isn't it will replace the page with what ever it writes out. The Document Object Model (DOM) can be used to add elements, text, etc. to the page without reloading it.

I suggest you read up on the Document Object Model (DOM):
Rough Guide to the DOM (http://www.sitepoint.com/article/rough-guide-dom/)
JavaScript tutorial - W3C DOM introduction (http://www.howtocreate.co.uk/tutorials/javascript/domintroduction)
http://www.quirksmode.org/dom/
http://www.quirksmode.org/js/dom.html
http://www.brainjar.com/
http://developer.apple.com/internet/webcontent/dom2i.html
http://developer.mozilla.org/en/docs/DOM:document
http://developer.mozilla.org/en/docs/Gecko_DOM_Reference
http://digital-web.com/articles/forms_usability_and_the_w3c_dom/
http://www.w3.org/DOM/



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum