Detecting a container by moving an element over it
I am making a simple drag'n'drop interface. I have a bunch of containers ("wrapper") and some dynamically added elements ("dragElement") in one of them. So I need when I move an element over another container, JS detects it and moves the element there when the drag is complete.
I tried to detect a container with "onmouseover" and "mouseup" when dragging an element, but was unsuccessful because in fact the mouse was always over the element being dragged. So how can I detect the container when dragging? In pure JS please ...
document.onmousedown = function(e) {
var dragElement = e.target;
if (!dragElement.classList.contains('draggable')) return;
var coords, shiftX, shiftY, detectPage;
startDrag(e.clientX, e.clientY);
document.onmousemove = function(e) {
moveAt(e.clientX, e.clientY);
};
wrapper.onmouseover = function(e) {
detectPage = e.target;
console.log(detectPage);
};
dragElement.onmouseup = function() {
finishDrag();
};
function startDrag(clientX, clientY) {
shiftX = clientX - dragElement.getBoundingClientRect().left;
shiftY = clientY - dragElement.getBoundingClientRect().top;
dragElement.style.position = 'fixed';
document.body.appendChild(dragElement);
moveAt(clientX, clientY);
};
function finishDrag() {
dragElement.style.top = parseInt(dragElement.style.top) - wrapper.getBoundingClientRect().top + 'px';
dragElement.style.position = 'absolute';
wrapper.onmouseup = function(e) {
var selectPage = e.target;
}
wrapper.appendChild(dragElement);
document.onmousemove = null;
dragElement.onmouseup = null;
};
function moveAt(clientX, clientY) {
var newX = clientX - shiftX;
var newY = clientY - shiftY;
if (newX < 0) newX = 0;
if (newX > wrapper.offsetWidth - dragElement.offsetWidth) {
newX = wrapper.offsetWidth - dragElement.offsetWidth;
}
dragElement.style.left = newX + 'px';
dragElement.style.top = newY + 'px';
};
return false;
};
source to share
Well, nobody helps. So, one day off to find a solution. All I can find is to remove the function finishDrag()
from dragElement.onmouseup
and change it to the code below.
In short, when it onmouseup
comes, dragElement
should go to display:none
, and now we can access the object next to the mouse cursor through elementFromPoint
. When we're done with that, we can easily detect the container, return the item to, display:block
and place it in that container ...
Hope this helps someone ...
dragElement.onmouseup = function(e) {
dragElement.style.display = 'none';
var selectPage = document.elementFromPoint(e.clientX, e.clientY);
dragElement.style.display = 'block';
dragElement.style.top = parseInt(dragElement.style.top) - selectPage.getBoundingClientRect().top + 'px';
dragElement.style.position = 'absolute';
selectPage.appendChild(dragElement);
document.onmousemove = null;
dragElement.onmouseup = null;
};
source to share