R
R
Ruslan Leviev2010-09-11 14:48:13
JavaScript
Ruslan Leviev, 2010-09-11 14:48:13

Drag'n'drop on dynamically created elements (jQuery)?

jQuery has a nice jQuery UI Draggable plugin that allows you to create drag'n'drop effects. It works quite simply: you need to call the .draggable() method for any existing element:
$('#test').draggable();<br>
If you try to call this method for a dynamically added element, then nothing will happen:

$('body').append('<div id="newblock">Новый элемент</div>');<br>
$('#newblock').draggable();<br>

The "new element" will not be able to be drag'n'drop. How can I do something similar to the .live() function here so that dynamically created elements also respond to these methods?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sererator, 2010-09-11
@Serator

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>jQuery UI Example Page</title>
    <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.4.custom.min.js"></script>
    <script type="text/javascript">
      $(function(){
        $('body').append('<div id="newblock">Новый элемент</div>');
        $('#newblock').draggable();
      });
    </script>
  </head>
  <body>
    <div>
      :)
    </div>
  </body>
</html>

Everything works great. Could you provide a more complete example.

3
3ds, 2010-09-11
@3ds

Too lazy to try, try livequery (works when cloned - adds draggable) cloning also creates an element dynamically and works, maybe it will work in your case.

$(".drag")
   .livequery(function(){
        $(this)
         .draggable({
                helper: 'clone',
                opacity: 0.7
               return: 'invalid'
          });
    });

examples: bit.ly/azEmUP

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question