You can do it by using a function call to create a next context for each handler (but see below), like this:
var ratings = new Array("happy", "clean");
for(y = 0; y < 2; y++)
{
for(x = 0; x < 5; x++)
{
fullname = ratings[y] + '_' + x;
(function(thisx, thisy) {
document.getElementById(fullname).onmouseover = function() {
star_rate(ratings[thisy], thisx, 1);
};
document.getElementById(fullname).onmouseout = function() {
star_rate(ratings[thisy], thisx, 2);
};
})(x, y);
}
}
That works by passing x
and y
as parameters into a function, which then sets up the event handlers using the arguments rather than the outer loop's version of x
and y
. (I've also removed the function names in the event handler assignments above. Using a name in a function expression [as opposed to a function declaration] is problematic in some browsers, more here. Also, you'd called them both onmouseover
, which probably isn't what you meant to do. :-) )
But that's not how I'd recommend doing it. It creates a new function for each element. Instead, I'd probably store the necessary information on the element itself as an attribute, and use a common function for all of this. That's what HTML5's data-
prefix is for (and it works now, today, even though technically not valid). Something vaguely like this:
var ratings = new Array("happy", "clean");
var element;
for(y = 0; y < 2; y++)
{
for(x = 0; x < 5; x++)
{
fullname = ratings[y] + '_' + x;
element = document.getElementById(fullname);
element.setAttribute('data-star-x', x);
element.setAttribute('data-star-y', y);
element.onmouseover = handleMouseOver;
element.onmouseout = handleMouseOut;
}
}
function handleMouseOver() {
star_rate(this.getAttribute('data-star-y'), this.getAttribute('data-star-x'), 1);
}
function handleMouseOut() {
star_rate(this.getAttribute('data-star-y'), this.getAttribute('data-star-x'), 2);
}
You could even use event bubbling (since mouseover and mouseout bubble) to hook the events on the overall container rather than each element, since you're getting the data from the element. (That's sometimes called "event delegation".)