I need to create several Divs dynamically, and I need to add \"onmouseover\" event to them. However, the JAVASCRIPT \"div.onmouseover = handler\" can\'t pass in parameters.
You can use a closure to do this:
myParam = "test";
div.onmouseover = function(){ alert(myParam); }
You can take advantage of closures to do this:
function createHandlerFor(a, b, c) {
return function(event) {
// This function will be called later, and it has access
// to 'a', 'b', and 'c'
};
}
Or using a named function (my preference, so call stacks and such are clearer);
function createHandlerFor(a, b, c) {
function myNiftyHandler(event) {
// This function will be called later, and it has access
// to 'a', 'b', and 'c'
};
return myNiftyHandler;
}
Use:
div.onmouseover = createHandler(1, 2, "three");
...or hook it up via addEventListener
(standards) or attachEvent
(IE < 8).
Although you could define the handler inline, doing so "closes over" everything that's in scope where you define it. Using a separate function and passing it parameters keeps the closure as small as possible, which is useful for memory management.
Closures are not complicated, but they have some interesting properties. More here.
You can create a closure.
div.onmouseover = function(){ handler(arguments,here); }