Copy events from one element to other using jquery

Accepted answer did not work for me as I use namespaces and other events (such as "paste") that are not a method in jQuery.

This worked for me:

function copyEvents(source, destination) {
    // Get source events
    var events = source.data('events');

    // Iterate through all event types
    $.each(events, function(eventType, eventArray) {
        // Iterate through every bound handler
        $.each(eventArray, function(index, event) {
            // Take event namespaces into account
            var eventToBind = event.namespace.length > 0
                ? (event.type + '.' + event.namespace)
                : (event.type);

            // Bind event
            destination.bind(eventToBind, event.data, event.handler);
        });
    });
}

If you want to copy all events from one object to another without cloning, you can do so by accessing the events data directly.

For instance, if you did:

$("#the_link").click(function(e){
    // do some stuff
    return false;
}).mouseover(function(e){
    // do some other stuff
});

You can access those event associates in the 'events' data of the element

var events = $("#the_link").data('events');

It will be an object whose keys represent the event type, each containing an array of event associations. Regardless, here's a simple example, not accounting for namespaces.

var events = $("#the_link").data('events');
var $other_link = $("#other_link");
if ( events ) {
    for ( var eventType in events ) {
        for ( var idx in events[eventType] ) {
            // this will essentially do $other_link.click( fn ) for each bound event
            $other_link[ eventType ]( events[eventType][idx].handler );
        }
    }
}

This one worked very well in my script.

$.each($('#original').data('events'), function() {
  // iterate registered handler of original
  $.each(this, function() {
    $('#target').bind(this.type, this.handler);
  });
});

I found it here (source): http://snipplr.com/view/64750/


You can clone an element and manipulate the new element however you want, however jQuery doesn't provide an easy way to copy event handlers from one element to another. However, the code that would do it would be:

var events = jQuery.data( originalElement, "events" );

for ( var type in events ) {
    for ( var handler in events[ type ] ) {
        jQuery.event.add( targetElement, type, events[ type ][ handler ], events[ type ][ handler ].data );
    }
}

But since it relies somewhat on jQuery internals, I would try to make a solution using clone.

Tags:

Jquery