I have a nice solution from my previous question that successfully clones images after being dropped.
Here is the code:
$(function() {
var makeDraggable = function(element) {
element.draggable({
revert: "invalid",
appendTo: "#droppable",
helper: "clone"
});
}
$( "#droppable" ).droppable({
activeClass: "ui-state-default",
hoverClass: "ui-state-hover",
drop: function(event, ui) {
var newClone = $(ui.helper).clone();
makeDraggable(newClone);
$(this).after(newClone);
}
});
// Initalise the program by making first draggable:
makeDraggable($(".draggable img"));
But the problem is I want to show only one image at a time in the targeted area. But currently all the dropped images are shown.
More specifically when user drops an image in the targeted area and later drags another image, the previous image should be removed from the dropped or targeted area and only the new image should be visible in the targeted area. See this demo: jsFiddle example
How do I solve this?
Instead of simply emptying the droppable
target area like the other answers do, I would add a class to the dropped items and then remove them upon a dragstart
event of a new draggable
. Also, it's nice to add a little fadeOut()
event when a new draggable is selected. However, as Ishettyl pointed out, one must also fadeIn()
the element again if the user decides not to drop the draggable. This can be done using a custom revert
function (see below).
The result is then something like this:
In my opinion this looks more elegant and doesn't confuse the user whether more items are allowed.
$(function() {
$(".draggable img").draggable({
revert: function (socketObj) {
if (!socketObj) {
if ($(this).hasClass("droppedItems")) {
$(this).fadeOut(function() {
$(this).remove();
});
} else {
$(".droppedItems").fadeIn();
return true;
}
}
},
helper: "clone",
start: function(event, ui) {
$(".droppedItems").fadeOut();
}
});
$( "#droppable" ).droppable({
activeClass: "ui-state-default",
hoverClass: "ui-state-hover",
drop: function(event, ui) {
$(".droppedItems").remove();
var newClone = $(ui.helper).clone();
newClone.addClass("droppedItems");
$(this).append(newClone);
}
});
});