Read the Jibbering.com Closures FAQ for more information on your problem. The functions do get added to every <select>, but the selectObj modified within those functions is the one that exists after the loop has run all the way through. One way to cure this problem is to create a separate scope to hold the current element:
Code:
function normalizeDDWidth() {
for(var i = 0, a = document.getElementsByTagName("select"); i < a.length; ++i) {
a[i].onmouseover = (function() {
var selectObj = a[i];
return function() {
selectObj.style.width = "auto";
};
})();
a[i].onblur = (function() {
var selectObj = a[i];
return function() {
if(selectObj.options[selectObj.selectedIndex].value !== '')
selectObj.style.width = "auto";
else
selectObj.style.width = "9em";
};
})();
}
}
... but a far better method (although one that may be unsuitable for your code, if it does things other than the snippet you've shown here) is to just use this to refer to the current element, and avoid creating all those unnecessary scopes:
Code:
function normalizeDDWidth() {
var overfunc = function() {
this.style.width = "auto";
};
var outfunc = function() {
if(this.options[this.selectedIndex].value !== '')
this.style.width = "auto";
else
this.style.width = "9em";
};
for(var i = 0, a = document.getElementsByTagName("select"); i < a.length; ++i) {
a[i].onmouseover = overfunc;
a[i].onblur = outfunc;
}
}
Bookmarks