Reputation: 51
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.
Upvotes: 5
Views: 4493
Reputation: 10830
It's a fragile approach from the start. You have a function to make a clone, and then you have a function to execute after cloning. Why not just call that function to occur after the cloning? Make a re-usable function that can be called from the click binding, or called directly from the cloning function.
If it's absolutely necessary, you could just use $(selector).click()
which will fire a click event.
[edit: I was not aware of the need to pass 'true' as per Fauntleroy's response either, so without that advice, my approach wouldn't work either. But the general advice of "this is probably a bad approach" stands]
Upvotes: 0
Reputation: 621
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 );
Upvotes: 21