The script I have been working on for a star rating system, saves the filled in stars with an onClick event and changes the onmouseover & onmouseout values to null so moving the mouse off them afterwards won’t mess that up, and the form has multiple ratings and a clear button at the bottom, which i need to have reset the onmouseover & onmouseout events, through the function below, but within those, ratings[y] and x are taken to be literal rather than what they contain, and makes the onmouse events fail because the parameters are incorrect. How do I put in the variables when changing the events this way?
var ratings = new Array("happy", "clean");
for(y = 0; y < 2; y++)
{
for(x = 0; x < 5; x++)
{
fullname = ratings[y] + '_' + x;
document.getElementById(fullname).onmouseover = function onmouseover() { star_rate(ratings[y], x, 1); };
document.getElementById(fullname).onmouseout = function onmouseover() { star_rate(ratings[y], x, 2); };
}
}
You can do it by using a function call to create a next context for each handler (but see below), like this:
That works by passing
xandyas parameters into a function, which then sets up the event handlers using the arguments rather than the outer loop’s version ofxandy. (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 bothonmouseover, 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: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”.)