Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI draggable is not working on newly created DOM element

I have some DOM element which is draggable using jQuery UI.All are working fine but when i create some element using jQuery , then they are not draggable at all. i.e

$('div.draggable').draggable(); //Existing element , it works :)
$('p.draggable').draggable() ; //Newly created paragraph with same class name, it doesnt work at all :(

Thanks in advance !!!

I am trying This :

<script type="text/javascript">
     $(document).ready(function(){
         $('body').append('<p class="draggable">Newly Created Paragraph</p>');
         $('p.draggable').draggable(); **//This is not working**
     });
</script>

However Somehow this is working

    <script type="text/javascript">
     $(document).ready(function(){
         $('body').append('<p class="draggable">Newly Created Paragraph</p>')
                 .find('p.draggable').draggable(); **This is working**

     });
</script>
like image 469
Vivek Avatar asked Mar 21 '12 06:03

Vivek


People also ask

Why draggable is not working?

Check whether your draggable object is already loaded in the viewport. If it is not, it won't work properly. JUST AFTER the draggable object to be absolutely sure that everything is loaded at the correct time. When you'll be sure everything is ok, then you'll be able to refactor.

What is jQuery draggable?

jQueryUI provides draggable() method to make any DOM element draggable. Once the element is draggable, you can move that element by clicking on it with the mouse and dragging it anywhere within the viewport.


2 Answers

I know its been a while, but this problem recently bugged me too. As someone else mentioned, you got to rerun .draggable() on the newly created item, but that doesn't work if you defined certain options in your .draggable(). Also what didn't work was putting the $().draggable() in a function and then calling the function after creating a new element (this trick does however work with resetting droppables - go figure).

Anyway, long story short -> Putting the $().draggable() setup in a function and then calling the function after creating new element DID WORK, but i had to TAKE IT OUT of the document ready function..... after i disabled that, it worked.

You can call that function as many times and it keeps on working after every created element. It seems if it's in the document.ready statement then its a 1 shot deal..

Hope that helps.

like image 108
Matt Avatar answered Sep 20 '22 22:09

Matt


You need to call draggable() after the newly created element is inserted into the DOM.

The reason being, is that the first line of code is only matching existing elements. Newly created elements aren't selected in that first line.

like image 25
Justice Erolin Avatar answered Sep 22 '22 22:09

Justice Erolin