How to make all div draggable with in a parent container
draggable, jquery, jquery-ui
Solution
You need to use the "live" function of jquery to add events and functions on future elements.
This code is borrowed from another post (http://stackoverflow.com/questions/1805210/jquery-drag-and-drop-using-live-events)
(function ($) {
$.fn.liveDraggable = function (opts) {
this.live("mouseover", function() {
if (!$(this).data("init")) {
$(this).data("init", true).draggable(opts);
}
});
return $();
};
}(jQuery));
Now instead of calling it like:
$(selector).draggable({opts});
...just use:
$(selector).liveDraggable({opts})
Problem
There is a `div` with id `parentDiv`, and there are some div with class `block1` in `parentDiv` divl like ``` <div id="btn"><input name="click" type="button" value="Click" class='button" /></div> <div id="parentDiv"> <div class="block1" style=" width:100px; height:100px; background:orange;">I am Block1</div> <div class="block1" style=" width:100px; height:100px; background:orange;">I am Block1</div> </div> ``` and In JQuery, div with class `block1`, are draggable. ``` $(function(){ $('.block1').draggable({ drag: function() { $('.block1').text('Drag Now!'); }, stop: function() { $('.block1').text('Stop Now!'); } }); }); ``` These div are working as aspect, but the problem is, if any new div with `block1` is appended in the `parentDiv` by clicking on btn input like ``` $('#btn').on('click', 'input.button', function(){ var $newDiv=$('<div class="block1" style=" width:100px; height:100px; background:green;">I am Block1</div>'); }); ``` that is not draggable. Yes, It will not work, because it was not in DOM. We are able to define a `click` event on `#btn` div to its children `input.button`, and if we add new input with class button in this `#btn` div, all will work as aspect. So my question is, Is there a way to make all div draggable with in a parent container `parentDiv`, like we can do with `#btn` div?