3

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. how can I pass parameters in those dynamic event handlers?

1
  • What parameters do you want passed in? Commented Apr 3, 2010 at 15:28

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can create a closure.

div.onmouseover = function(){ handler(arguments,here); }

Comments

0

You can use a closure to do this:

myParam = "test";
div.onmouseover = function(){ alert(myParam); }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.