I am trying to create a function so that i can have multiple drag/droppables in a page. For that i made the following:
function apDrag(dragId,container) {
$(function() {
$('#'+dragId).draggable({
revert: "invalid",
drag: function(e) {
var currentPos = $('#'+dragId).position();
$('#data').html('Left: '+currentPos.left+ ' Top: '+currentPos.top);
}
});
$('#'+container).droppable({
tolerance: 'fit',
greedy: true,
drop: function( event, ui ) {
// For some reason "dragId" defaults to "dragger2" here
// console.log(dragId); = dragger2; even though first function passes "dragger1" as dragId
$('#'+dragId).draggable({revert:"invalid"});
pos = $('#'+dragId).position();
cPosLeft = pos.left;
cPosTop = pos.top;
$('#data').html('Left: '+cPosLeft + ' Top: '+ cPosTop);
$('#'+dragId).html('ID: <b>'+dragId+'</b>');
}
});
});
}
apDrag('dragger','container');
apDrag('dragger2','container');
The problem here is that for some reason the "dragId" being passed into the drop function of the droppable, always become the same, and are not "dragger1", "dragger2" as it should be. It always reverts to "dragger2" for both of the divs.
PS: The reason I am creating a droppable for each function is that they eventually will have different settings for each draggable.
Please see fiddle: here for a better explanation
Thanks to A. Wolff, i found that using:
ui.draggable
in the drop function, i could get the correct id of the dragged div:
$('#'+container).droppable({
tolerance: 'fit',
greedy: true,
drop: function( event, ui ) {
var correctID = $(ui.draggable).attr("id");
// id of dragged element is now "correctID"
}
});
A. Wolff also updated the fiddle here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.