How can I pass arguments to event handlers in jQuery?

Solution 1:

The simplest way is to do it like so (assuming you don't want any of the event information passed to the function)...

$("#myid").click(function() {
    myfunction(arg1, arg2);
});

jsFiddle.

This create an anonymous function, which is called when the click event is triggered. This will in turn call myfunction() with the arguments you provide.

If you want to keep the ThisBinding (the value of this when the function is invoked, set to the element which triggered the event), then call the function with call().

$("#myid").click(function() {
    myfunction.call(this, arg1, arg2);
});

jsFiddle.

You can't pass the reference directly in the way your example states, or its single argument will be the jQuery event object.

If you do want to pass the reference, you must leverage jQuery's proxy() function (which is a cross browser wrapper for Function.prototype.bind()). This lets you pass arguments, which are bound before the event argument.

$("#myid").click($.proxy(myfunction, null, arg1, arg2));   

jsFiddle.

In this example, myfunction() would be executed with its ThisBinding intact (null is not an object, so the normal this value of the element which triggered the event is used), along with the arguments (in order) arg1, arg2 and finally the jQuery event object, which you can ignore if it's not required (don't even name it in the function's arguments).

You could also use use the jQuery event object's data to pass data, but this would require modifying myfunction() to access it via event.data.arg1 (which aren't function arguments like your question mentions), or at least introducing a manual proxy function like the former example or a generated one using the latter example.

Solution 2:

$("#myid").on('click', {arg1: 'hello', arg2: 'bye'}, myfunction);

function myfunction(e) {

    var arg1 = e.data.arg1;
    var arg2 = e.data.arg2;

    alert(arg1);
    alert(arg2);

}

//call method directly:
myfunction({
    arg1: 'hello agian', 
    arg2: 'bye again'
});

Also allows you to bind and unbind specific event handlers using the on and off methods.

Example:

$("#myid").off('click', myfunction);

This would unbind the myfunction handler from #myid