Richard Knop
Richard Knop

Reputation: 83745

Draggable stops working after I reload a part of web page with AJAX

I have implemented draggable and droppable jquery functions. They work.

However, they stop working if I reload a part of the website.

For example, I reload a div containing draggable items via AJAX (to get updated items) and suddenly I cannot drag and drop these new items. Though I do not reload the part of the web page with javascript code so it should still work.

Upvotes: 3

Views: 3841

Answers (3)

Adam Spiers
Adam Spiers

Reputation: 17916

N.B. as of JQuery 1.7, .live() is now deprecated in favour of .on(). However, either way the question remains: which type of event should be bound to in order to automatically re-attach the draggable functionality after the AJAX reload occurs? I tried load, change, mousedown, click ... none of them worked. Furthermore, the solution Justin linked to is only applicable when using the simplemodal plugin.

The solution I found is to extract the code which sets the draggable(s) and/or droppable(s) into a separate function which can then be reinvoked by the AJAX response after it reloads the relevant part of the page.

So the main Javascript code becomes:

function init_draggables_and_droppables() {
    $(".draggable").draggable({ revert: 'invalid' });
    ...
}

jQuery(function($) {
    init_draggables_and_droppables();
    ...
});

and then the AJAX response contains:

jQuery("div.to-reload").replaceWith(reloaded);
init_draggables_and_droppables();

Works nicely!

Upvotes: 4

Manu Clementz
Manu Clementz

Reputation: 1797

You have to use the live() method for this. Take a look at the documentation : .live()

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245479

When you reload the div containing the draggable items, you are removing the draggable functionality from them (they are new DOM elements rather than the old ones that had draggable attached to them).

You need to re-attach the draggable functionality each time you load those divs. Here's an example of how to use jQuery.live() to achieve what you need:

JQuery Live and Draggable

Upvotes: 3

Related Questions