jQuery: copy events from one element to another

At the moment, I improve my ApToggleSwitch plugin and stumbled over a problem which leads to a nice jQuery function I want to share. Perhaps this code can be useful for you!

The problem was that I have to copy a special event from one html element to another – in my case I only wanted the change event to be copied. I found some posts how to copy events, but the solutions did not work perfectly, so I had to merge the solutions presented in this thread.

After that I transfered this code to a jQuery function that is applicable to jQuery object and added a filter parameter, so only specific event types can be copied.

Code

$.fn.copyEvents = function( to, filter )
{
    var to = to.jquery ? to : jQuery(to);
    var filter = filter ? filter.split(" ") : null;
    var events = this[0].events || jQuery.data(this[0], "events") || jQuery._data(this[0], "events");

    return this.each(function()
    {
        if (!to.length || !events) {
            return;
        }

        $.each(events, function(eventType, eventArray) {
            $.each(eventArray, function(index, event) {
                var eventToBind = event.namespace.length > 0
                    ? (event.type + '.' + event.namespace)
                    : (event.type);
                if (filter && $.inArray(eventToBind, filter) == -1) {
                    return true;
                }
                to.bind(eventToBind, event.data, event.handler);
            });
        });
    });
}

Usage

// Add some events to a element
$('#element').click(function() { });
$('#element').dblclick(function() { });
$('#element').change(function() { });

// Default usage, copy *all* events from one element to another
$('#element').copyEvents('#another-element');

// ... or you can copy only specific event types
$('#element').copyEvents('#another-element', 'change click');

Thanks to antur123 and Brandon Aaron/yckart!

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha * Time limit is exhausted. Please reload CAPTCHA.