Why doesn't this javascript bind the correct parameters with the event? -


in code supposed bind rollover effect each <area> tag in <map> element.

function initlinks(webrt) {   var areas = document.queryselectorall("map#streetmap > area");   var links = new array(areas.length);   (var i=0; i<links.length; i++) {     links[i] = new image(786,272);     links[i].src = webrt+"templates/default/sketches/links"+(i+1)+".png";     areas[i].onmouseover=function(){switchlinkimg(webrt+"templates/default/sketches/links"+(i+1)+".png");};     areas[i].onmouseout=function(){switchlinkimg(webrt+"templates/default/sketches/links.png");};   } } 

strangely, each <area> onmouseover event tries load non-existing image: /templates/default/sketches/links6.png. why keep variable i has incremented 6 global variable rather take string passing function?

how fix this?

note: no jquery!

try using following code:

function initlinks(webrt) {     var areas = document.queryselectorall("map#streetmap > area");     var links = new array(areas.length);     (var i=0; i<links.length; i++) {         (function(index) {             links[index] = new image(786,272);             links[index].src = webrt+"templates/default/sketches/links"+(index+1)+".png";             areas[index].onmouseover=function(){switchlinkimg(webrt+"templates/default/sketches/links"+(index+1)+".png");};             areas[index].onmouseout=function(){switchlinkimg(webrt+"templates/default/sketches/links.png");};         })(i);     } } 

you should wrap i variable closure. otherwise gets incremented.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -