How do you copy an event handler from one element to another? For example:
$('#firstEl')
.click(function() {
alert("Handled!");
})
;
// here's where the magic happens
$('#secondEl').click = $('#firstEl').click; // ????
Note that the second element is being processed at a different time to when the first element is getting its handler, meaning that this:
$('#firstEl, #secondEl').click(function() { ... });
...won't work.
Is this what you are looking for?
http://www.learningjquery.com/2007/01/copy-events-from-one-element-to-another
$('#secondEl').click = $('#firstEl').click.bind($('#secondEl'));
Assuming you are using Prototype JS (http://www.prototypejs.org/api/function/bind)
This question was already answered but for future reference: you could copy them by iterating the events of the original element and binding their handlers to the target.
> see edit below!
This is handy when you have no control of the original element (e.g. when using a plugin) and just want to clone the behavior of a certain element.
Edit: Access to an elements event handlers has been changed in later jQuery versions. This should work for newer versions:
Cheers
You might be interested in the triggerHandler method
You can't easily (and probably shouldn't) "copy" the event. What you can do is use the same function to handle each:
Alternatively you could actually fire the event for the first element in the second handler:
Edit: @nickf is worried about polluting the global namespace, but this can almost always be avoided by wrapping code in an object:
or wrapping your code in an anonymous function and calling it immediately: