user531380
user531380

Reputation: 43

JQuery: Transferring Behaviors to Cloned Objects

I'm trying to quickly make copies of a class by binding the clone() method to the doubleclick event. My code, so far is:

<style type="text/css">
.draggable { float:left; clear: both; }
</style>
<script type="text/javascript">
$(function() {
    copyit = function() {
        $(this).clone().appendTo("body").css('position','absolute').draggable();
    }
    $('.draggable').dblclick(copyit);
    $('.draggable').draggable();
});
</script>

<div class="draggable">Hi There!</div>
<div class="draggable">What's up?</div>

Everything works, except I can't get the cloned elements to clone themselves once they are added to the DOM. Any help is greatly appreciated.

Upvotes: 2

Views: 415

Answers (2)

Pointy
Pointy

Reputation: 413737

Set up the double-click handler with .live():

$('.draggable').live("dblclick", copyit);

Upvotes: 1

Matt Evanoff
Matt Evanoff

Reputation: 966

My guess is that you are not binding the dblclick event to the new DOM nodes. In this case you actually have 2 ways you can accomplish this:

  1. You can make the dblclick a live (or delegate) event like this: $('.draggable').live('dblclick', copyit); see: http://api.jquery.com/live/ http://api.jquery.com/delegate/

  2. You can make the clone copy the events of the object by passing it true, like this: $(this).clone(true).appendTo("body").css('position','absolute').draggable(); see: http://api.jquery.com/clone/

Upvotes: 2

Related Questions