Reputation: 371
I'm trying to use jquery draggable and droppable.
I have multiple draggables and multiple droppables on my page.
The drga and drop works fine but the issue is that when I drag and drop a div onto 1 droppable, it will get cloned in other droppables on my page as well... also, when I move the draggables inside the droppables, they get multiplied again.
To explain this issue, I've created this FIDDLE
and this is my entire code:
(function ($) {
$.fn.liveDraggable = function (opts) {
this.live("mouseover", function() {
if (!$(this).data("init")) {
$(this).data("init", true).draggable(opts);
}
});
return this;
};
}(jQuery));
$('.drag').liveDraggable({
helper: 'clone',
cursor: 'move'
});
var x = null;
$(".droppable").droppable({
drop: function(e, ui) {
var parent = $(".droppable");
var x = ui.helper.clone();
var img = $(x)
var leftAdj = (ui.position.left - parent.offset().left);
var topAdj = (ui.position.top - parent.offset().top);
if (x.hasClass("outside")) {
x.css({
left: leftAdj,
top: topAdj
});
x.removeClass("outside");
}
x.draggable({
helper: 'original'
});
x.find('.ui-resizable-handle').remove();
x.resizable();
x.appendTo('.droppable');
ui.helper.remove();
}
});
Drag the red divs onto the black divs and you should see the issue.
Could someone please advise on this issue?
Any help would be appreciated.
EDIT:
Getting close but still not quite there: https://jsfiddle.net/qkhunz8k/2/
Upvotes: 0
Views: 845
Reputation: 7464
Edit: Apparently I'm not communicating very well. Let me try this again. All of your droppables have the class droppable
. As you say, of course they do. That is the purpose of the class.
However, in your code, when you say x.appendTo('.droppable')
, this is the source of your duplicates. It is appending to every element which has the droppable
class.
I'm not suggesting that you change or remove the droppable class. I'm not suggesting that you change all of your jquery selectors. I'm only suggesting that when you do your .appendTo
, perhaps you should only be appending it to the droppable
which is the target. Not all of them. Does that make sense? You can do this by doing x.appendTo(this)
. Just change that one line, and see if the duplicate problem goes away.
$(".droppable").droppable({
...
x.appendTo(this);
The only thing this change will do is change the number of elements your draggable gets appended to. It wouldn't cause any other changes. But I think it will solve your original problem.
As an aside, might I suggest that you would get better results by changing one other line? If you were to use the ui.draggable
instead of the ui.helper
, you might find that the css positioning would be a little easier to manage, and that you wouldn't need to manipulate the top
and left
properties so much. Just a thought.
var x = ui.draggable.clone();
updated modification of your fiddle here
Upvotes: 1