I have DOM is like this:
<a href='javascript:void(0)' id='link1'>Element with events bound initially</a> <a href='javascript:void(0)' id='link2'>Element to which events are bound in future</a>
And this javascript:
$(function(){ $('#link1').bind('click',function(){alert('do something to make me happy');}) });
Now some time in future i want to copy all events bound on link1 to link2. I am doing it as written below please suggest some better way if possible or available.
var _elmEvents = $(#link1).data('events'); if (_elmEvents) { $.each(_elmEvents, function (event, handlers) { $.each(handlers, function (j, handler) { $('#link2').bind(event, handler); }); }); }
To clone an element using jQuery, use the jQuery. clone() method. The clone() method clones matched DOM Elements and select the clones. This is useful for moving copies of the elements to another location in the DOM.
clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. Where possible, it is recommended to avoid cloning elements with this attribute or using class attributes as identifiers instead.
First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With