I want to use JavaScript to check if one div
element (that can be dragged) is touching another div
element.
Here is some code:
<div id="draggable" style="position: absolute; top: 100px; left: 200px; background-color: red; width: 100px; height: 100px;"></div>
<div style="background-color: green; width: 100px; height: 100px;"></div>
Can this be done?
If so, how?
Edit: I do not want to use jQuery, just plain old JavaScript!
A more complete solution
Below is a "plain old JavaScript" rewrite of the overlap detection function found in this answer to the question titled "jQuery/Javascript collision detection".
The only real difference between the two is the replacement of the use of jQuery to get element position and width for calculating the bounding box.
Surprisingly, native JavaScript makes this task easier with the well-supported (IE4+)
Element.getBoundingClientRect()
method, which returns the four values needed to create the position matrix returned by thegetPositions
function.I added a click handler for the boxes as a simple demonstration of how you might use the function to compare a target (clicked, dragged, etc.) element to a set of selected elements. I will concede, however, that jQuery makes DOM selection and event binding much easier than native JS.
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.
Use
element.getBoundingClientRect()
anddocument.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.