I need help with a simple functon for a gallery.

Discussion in 'JavaScript' started by JonKenneth, Apr 24, 2010.

  1. #1
    Im having a litle trouble with a gallery im working on.
    I have a table with 8 tumbnails and a large image that shall change when i click the tumbnails.
    The ting is that no matter what tumb i click, it swith to the eight image.:mad:

    Thanks for any help.:eek:

    
    function clickhandler(){
    	for(var i=1; i<=8; i++){
    		var imgName="img"+i;
    		document.getElementById(imgName).onclick=function() { imgChange(imgName); }
    	}
    }
    
    function imgChange(newImg){
    	document.getElementById("mainImg").src=document.getElementById(newImg).src;
    }
    
    Code (markup):

     
    JonKenneth, Apr 24, 2010 IP
  2. drknght

    drknght Peon

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    The problem you are encountering is due to the existence of closures within JavaScript. The closure for the onclick handler includes the variable imgName, which at the end of the loop is pointing to a single constant id - hence the repeated display of just that image.

    Try this revised code instead. Note that I have replaced the use of the local variable in the closure with the element id of the current function context (this).

    Hope this helps!

    ~drknght
     
    drknght, Apr 24, 2010 IP
  3. JonKenneth

    JonKenneth Peon

    Messages:
    9
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks! I'm used to program in php, so this object oriented programing is a very new way to think for me.
     
    JonKenneth, Apr 25, 2010 IP