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. Thanks for any help. 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):
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
Thanks! I'm used to program in php, so this object oriented programing is a very new way to think for me.