I want to use JavaScript to check if one div
element (that can be dragged) is touching another div
element.
Here is some code:
Update: I realize now that this only accounts for the intersection of the top left corner of the target element and therefore, doesn't provide a complete solution. But I'll leave it up for posterity in case someone finds it useful for other purposes.
element.getBoundingClientRect()
and document.elementFromPoint()
You can use element.getClientBoundingRect()
(src) to get the position of the target (clicked, dragged, etc.) element.
Temporarily hide the target element, then use document.elementFromPoint(x, y)
(src) to get the top-most element at that position, and then check it's class name for comparison (you could compare any attribute or property instead, if you prefer).
To achieve cross-browser compatible behavior from this method read: document.elementFromPoint – a jQuery solution (You don't have to use jQuery to achieve this result. The method can be replicated in pure JS.)
Addendum:
I am only showing the function for detecting overlap instead of showing drag-and-drop or drag-to-move functionality because it isn't clear which of those, if either, you are trying to implement and there are other answers showing how to accomplish various drag patterns.
In any case, you can use the detectCollision()
function below in combination with any drag solution.
var box2 = document.getElementById('box2'),
box3 = document.getElementById('box3');
box2.onclick = detectCollision;
box3.onclick = detectCollision;
function detectCollision(e) {
var elem = e.target,
elemOffset = elem.getBoundingClientRect(),
elemDisplay = elem.style.display;
// Temporarily hide element
elem.style.display = 'none';
// Check for top-most element at position
var topElem = document.elementFromPoint(elemOffset.left, elemOffset.top);
// Reset element's initial display value.
elem.style.display = elemDisplay;
// If a top-most element is another box
if (topElem.className.match(/box/)) {
alert(elem.id + " is touching " + topElem.id);
} else {
alert(elem.id + " isn't touching another box.");
};
}
#box1 {
background-color: LightSeaGreen;
}
#box2 {
top: 25px;
left: -25px;
background-color: SandyBrown;
}
#box3 {
background-color: SkyBlue;
}
.box {
position: relative;
display: inline-block;
width: 100px;
height: 100px;
}
.clickable {
cursor: pointer;
}