JSFiddle - React, Tailwind, and code Playground
HTML
<div class="blocks">
<div class="block">Block 1</div>
<div class="block">Block 2</div>
<div class="block">Block 3</div>
</div>
<a class="block-add" href="javascript:void(0)">Add a block</a>
CSS
.blocks {
display: inline-block;
width: 100%;
}
.block {
float: left;
background: black;
color: white;
width: 100px;
height: 100px;
margin: 10px;
text-align: center;
vertical-align: middle;
line-height: 100px;
}
JavaScript
$.fn.extend({
/**
* Children of the element with the given selector
* will automatically be made draggable
* @param {String} selector
* The selector of the child / descendant elements
* to automatically be made draggable
* @param {Object} opts
* The options that would normally be passed to the
* draggable method
* @returns
* The jQuery array for chaining
*/
draggableChildren: function(selector, opts) {
// On using event delegation to automatically
// handle new child events
$(this).on("mouseover", selector, function() {
// Check that draggable not already initialized
if(!$(this).is(":ui-draggable"))
// Initialize draggable
$(this).draggable(opts);
});
// Return this for chaining
return this;
}
});
$(function() {
$(".blocks").draggableChildren(".block", {
drag: function() {
$(this).text("Dragging");
},
stop: function() {
$(this).text("I'm out of place");
}
});
var n = $(".blocks .block").length;
$(".block-add").click(function() {
$(".blocks").append('<div class="block">Block ' + (++n) + '</div>');
});
});