I am currently developing a drag-and-drop application using only Javascript. I have successfully implemented the dragging functionality, allowing elements to be moved randomly within the page. However, I now face the challenge of creating a drop zone with 9 boxes (divs) that need to receive these dragged elements. I am seeking a suitable approach to achieve this task efficiently. My initial thought is to set these divs as 'absolute' and reposition them using the top and left attributes. But how should I proceed from here? How can the dragged div, activated onmousedown, detect where it should drop when released onmouseup? For instance, if I select div number 1, it should be dropped into target number 1.
Below is the snippet of Javascript code I am currently employing for selecting and dragging:
window.onload = function() {
var el = document.getElementById('block1');
var mover = false, x, y, posx, posy, first = true;
el.onmousedown = function() {
mover = true;
};
el.onmouseup = function() {
mover = false;
first = true;
};
el.onmousemove = function(e) {
if (mover) {
if (first) {
x = e.offsetX;
y = e.offsetY;
first = false;
}
posx = e.pageX - x;
posy = e.pageY - y;
this.style.left = posx + 'px';
this.style.top = posy + 'px';
}
};
};