Reputation: 369
I have a series of icons which are dragged onto a canvas / map. When the icon has been dragged - the icon is replaced in it's original position, so the user can drag a second icon (of the same picture) onto the canvas.
I have made it so all items are .draggable()
and when the first icon is dragged onto the map I simply use jquery .append()
to recreate the icon in it's original position.
My problem is that is creates the second instance of the icons - but doesn't create any more after that - leaving a blank space.
I need this to be an infinite loop so the user can drop as many of the same images as possible onto the canvas.
My code is as follows, I create a randomly generated number to ensure I can assign .draggable()
to it:
$('img#icon').draggable({
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
var left = Math.abs(Stoppos.left);
var top = Math.abs(Stoppos.top);
$(this).css('left: ' + left);
$(this).css('top: ' + top);
var rand = [randomly generated number];
var src = $(this).attr("src");
var cl = $(this).attr("class");
var id = $(this).attr("id");
var img = "<img src='"+src+"' id='"+id+"' class='"+cl+" "+rand+"' />";
$(this).parent().append(img);
$("img."+rand).draggable();
}
});
So with the above, after I have dragged img.rand
onto the canvas - this is not replaced in it's original position.
Hope this makes sense and help appreciated as ever.
Upvotes: 0
Views: 251
Reputation: 1837
You don't need a infinite loop for this. What you need is to make the canvas droppable
. Remove the dragstop
function and add your code in the droppable function as:
$('#canvas').droppable({
accept:'.icons', //remove this if you want to append manually
drop:function(event,ui){
//Code for appending manually if you don't use accept
}
});
For the series of icons make it draggable as clone so that you can drag 'n' no. of same icon onto canvas:
$('.icons').draggable({helper: "clone"});
For more info on droppable UI refer API DOC.
Upvotes: 1