Change your Add Button and Remove Button event as follows:
$(".remove").click(function(){ $(".currentDiv").remove(); }); var z = 1; $('#button').click(function (e) { $(".currentDiv").removeClass("currentDiv"); $('<div />', { class: 'draggable ui-widget-content', text: $('textarea').val(), appendTo: '.middle-side', draggable: { containment: 'parent', start: function( event, ui ) { $(this).css('z-index', ++z); }, drag: function() { $(".currentDiv").removeClass("currentDiv"); $(this).addClass("currentDiv"); }, } }).addClass('placement currentDiv');
Thus, when you create a new div, all currentDiv classes are removed on this line:
$(".currentDiv").removeClass("currentDiv");
Then the currentDiv class currentDiv added to the created div in the last line. Therefore, the always created div has the currentDiv class.
Then add this block to the end of your JS:
$('body').on('click', '.draggable', function () { $(".currentDiv").removeClass("currentDiv"); $(this).addClass("currentDiv"); });
The above block causes that when you click on each item you drag, it is selected as the current div, so click the Remove button, delete it.
Check JSFiddle Demo
The background color is also added to the demo: red for currentDiv, you can remove it.
source share