In the below code, the created link element (ap) correctly displays the right customer number in the instruction “ap.href="javascript:CallCustomer("+i+")";†but it displays the wrong icon number in the instruction “ap.onmouseover= function(){ t.innerHTML = "icon " + i};â€. It always shows the last value of “i†in the for loop plus 1, no matter what link the mouse is over. How to fix it ? function init() { t = document.getElementById("test"); ctn = document.getElementById('container'); for( var i= 0; i < total_icons; i++) { var newdiv = document.createElement('div'); var divIdName = 'icon_pos'+i; newdiv.setAttribute('id',divIdName); ctn.appendChild(newdiv); var alink = document.createElement('a'); var aIdName = 'alink'+i; alink.setAttribute('id',aIdName); newdiv.appendChild(alink); var ap = document.getElementById('alink'+i); ap.href = "javascript:CallCustomer("+i+")"; ap.onmouseover= function(){ t.innerHTML = "icon " + i}; var icon_img = document.createElement('IMG'); var imIdName = 'icon'+i; icon_img.setAttribute('id', imIdName); alink.appendChild(icon_img); } //... } function CallCustomer( number ) { alert("You called Customer "+number); }
Yep, it will. Because you create a new function this function uses the global scope, where i is the same as used in the for loop, which by the time of the mouseover event, has the last value from the for loop condition. The simplest solution is to put the onmouseover function outside the for and call it like you call CallCustomer(), with the current value of i. Something like that: ap.onmouseover= "javascript: mOver("+i+")"; Code (markup): and then you have function mOver(value) { document.getElementById('test').innerHTML = "Icon "+value; } Code (markup): somewhere in the code..