How do you copy an event handler from one element to another? For example:
$(\'#firstEl\')
.click(function() {
alert(\"Handled!\");
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!
// iterate event types of original
$.each($('#original').data('events'), function() {
// iterate registered handler of original
$.each(this, function() {
$('#target').bind(this.type, this.handler);
});
});
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:
$.each($._data($('#original').get(0), 'events'), function() {
// iterate registered handler of original
$.each(this, function() {
$('#target').bind(this.type, this.handler);
});
});
Cheers