Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery trigger not firing after clone

I have a div in my code and when I clone it wil not directy fire an event. Here's the code;

<div id="draggable" onclick="alert(1);" class="ui-widget-content drag">
    <p>Drag me to my target</p>
</div>
<div id="here">
</div>

<script type="text/javascript">
    $("#draggable").clone().removeAttr("id").attr('id', 'draggable2').appendTo("#here");
    $("#draggable2").trigger('onclick');
</script>

When I then click on the cloned element it will fire the event normaly.

If I change the script to let the original element trigger it works fine also:

<script type="text/javascript">
    $("#draggable").clone().removeAttr("id").attr('id', 'draggable2').appendTo("#here");
    $("#draggable").trigger('onclick');
</script>

Also a bind function works fine:

<script type="text/javascript">
    $("#draggable").clone().removeAttr("id").attr('id', 'draggable2').appendTo("#here");
    $("#draggable2").bind('click', function () { alert('2'); });
    $("#draggable2").trigger('click');
</script>

Has any one an idea on how to fire the 'standard' onclick of the cloned element directly after cloning.

like image 813
patrick Avatar asked Nov 30 '22 06:11

patrick


1 Answers

In order to clone an element AND its events, you must pass "true" as the first argument. To pass the events of its children, you must also pass "true" as its second argument.`

$myClone = $('#element').clone( true, true );

http://api.jquery.com/clone/

like image 51
Fauntleroy Avatar answered Dec 02 '22 20:12

Fauntleroy