Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Mar 2006
    Location
    buena park, ca
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question my code stops looping

    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

    Code:
    <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>

  • #2
    Senior Coder
    Join Date
    Feb 2006
    Location
    USA
    Posts
    1,013
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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
    JavaScript tutorial - W3C DOM introduction
    http://www.quirksmode.org/dom/
    http://www.quirksmode.org/js/dom.html
    http://www.brainjar.com/
    http://developer.apple.com/internet/...ent/dom2i.html
    http://developer.mozilla.org/en/docs/DOM:document
    http://developer.mozilla.org/en/docs..._DOM_Reference
    http://digital-web.com/articles/form...d_the_w3c_dom/
    http://www.w3.org/DOM/
    Learn CSS. | SSI | PHP includes | X/HTML Validator | CSS validator | Dynamic Site Solutions
    Java != JavaScript && JScript != JavaScript
    Design/program for Firefox (and/or Opera), apply fixes for IE, not the other way around.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •