Skip to content Skip to sidebar Skip to footer

JQuery Draggable - What Happens If It Is Applied Twice To An Element?

Until recently I had this set up, which was called multiple times: $('.rsh') .draggable('destroy')

Solution 1:

No, there won't be extra handlers bound. jQuery registers the initialized instance to the element and won't create a new instance of the same widget for the same element.

As you're worried about handlers, here's a quick check (jQuery 1.8+ and UI 1.9+):

$('div').draggable();
console.log( $._data($('div')[0], 'events') );
$('div').draggable();
console.log( $._data($('div')[0], 'events') );

Fiddle

As you can see, the attached handlers object is not altered after trying to initialize a new draggable instance on the same element.

edit: Subsequent calls with parameters won't be ignored though, rather they will extend the existing widget as shown on @Jason Sperske's answer.


Solution 2:

Subsequent calls to .draggable() extend previous calls when attached to the same object (and not replace them as I had originally thought). See this example (extended from Fabrício Matté's) (demo)

<div>foo</div>
<script>
 $('div').draggable({
  start: function () {
    console.log("drag 1");
  }
 });
 console.log($._data($('div')[0], 'events'));
 $('div').draggable({
  stop: function () {
    console.log("drag 2");
  }
 });
 console.log($._data($('div')[0], 'events'));
</script>

In the console.log you see only these messages:

drag 1 <- on start
drag 2 <- on stop

Post a Comment for "JQuery Draggable - What Happens If It Is Applied Twice To An Element?"