Draggable position
HTML
<div class="dropzone">
<div class="drag" draggable="true">
</div>
</div>
CSS
.dropzone {
width: 300px;
margin: 0 auto;
height: 300px;
background-color: #fff;
border: 1px solid #000;
position: relative;
}
.drag {
width: 20px;
height: 20px;
background-color: black;
position: absolute;
top: 100%;
left: 50%;
}
JavaScript
;
(function($, undefined) {
var dragging;
$(function() {
$('.dropzone').on({
'dragover dragenter': dragover,
'drop': drop
}).on({
'dragstart': dragstart,
'dragend': dragend
}, '.drag');
});
function dragstart(e) {
e.stopPropagation();
var dt = e.originalEvent.dataTransfer;
if (dt) {
dt.effectAllowed = 'move';
dt.setData('text/html', '');
dragging = $(this);
// Set the position of the mouse relative to the element at 0,0
dt.setDragImage(dragging.get(0), 0, 0);
}
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
if (dt && dragging) {
dt.dropEffect = 'move';
dragging.hide(); // Hide the element while dragging
}
return false;
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
if (dragging) {
var dropzone = $(this);
// Get the offset of the dropzone relative to the window
var offset = dropzone.offset();
// Set the offset of the drag relative to the dropzone
dragging.css({
'top': e.clientY - offset.top,
'left': e.clientX - offset.left
});
dragging.trigger('dragend'); // Trigger the dragend
}
return false;
}
function dragend(e) {
if (dragging) {
dragging.show();
dragging = undefined;
}
}
}(jQuery));