Burnee
Burnee

Reputation: 2623

jQuery clone api doesn't clone the native javascript events

If I add a native event handler to an element using the "element.onclick = function() {...};" syntax, and later I clone the element with the jQuery clone api, using 'true' parameter, then the cloned element doesn't get the natively added event handler. How can I solve it, if the native syntax that I've used above is a must (so pls don't give me an answer like "use $(element).click(function(e){...});", etc..).

In code:

EDIT: pls check on jsfiddle: http://jsfiddle.net/86f96/

Upvotes: 1

Views: 523

Answers (2)

leo.vingi
leo.vingi

Reputation: 1852

You can't have 2 elements with the ID btn on the same page.

EDIT:

I looked at the jsfiddle, and sadly I can't come up with a different solution, other than attaching the click event again, after appending the clone

EDIT 2:

This is as close as I got, without changing the native JS onclick event. So if for some reason, you can't change the previously defined function, this would help:

var element = document.getElementById('element');
document.getElementById('element').onclick = function() { alert( 'clicked' ); };
//...
var clone = $(element).clone(true);
var native_click_function = $(element)[0].onclick;
$(element).remove();
clone.appendTo('body').click(function(){
    native_click_function();
});

The code is taken from the JS fiddle.

Upvotes: 1

Abe Petrillo
Abe Petrillo

Reputation: 2447

append and appendTo don't pass the events. Some see it as a bug, some see it as a feature, alas the only way around it is to use live() or redefine the events.

Upvotes: 0

Related Questions