10

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!

gfullam
  • 11,531
  • 5
  • 50
  • 64
The_HTML_Man
  • 347
  • 1
  • 4
  • 13
  • 2
    possible duplicate of [check collision between certain divs?](http://stackoverflow.com/questions/9768291/check-collision-between-certain-divs) – Aracthor Apr 28 '15 at 10:30
  • By counting elements top / left and width / height You can do it :) http://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element PS: comment above is telling the same as I am... oh well... :D – Mr.TK Apr 28 '15 at 11:20

2 Answers2

9

A plain old JS 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.

Native JavaScript makes this task easy via the Element.getBoundingClientRect() method, which returns the four values needed to create the position matrix returned by the getPositions 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.

var boxes = document.querySelectorAll('.box');

boxes.forEach(function (el) {
  if (el.addEventListener) {
      el.addEventListener('click', clickHandler);
  } else {
      el.attachEvent('onclick', clickHandler);
  }
})

var detectOverlap = (function () {
    function getPositions(elem) {
        var pos = elem.getBoundingClientRect();
        return [[pos.left, pos.right], [pos.top, pos.bottom]];
    }

    function comparePositions(p1, p2) {
        var r1, r2;
        if (p1[0] < p2[0]) {
          r1 = p1;
          r2 = p2;
        } else {
          r1 = p2;
          r2 = p1;
        }
        return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function (a, b) {
        var pos1 = getPositions(a),
            pos2 = getPositions(b);
        return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
    };
})();

function clickHandler(e) {
    
    var elem     = e.target,
        elems    = document.querySelectorAll('.box'),
        elemList = Array.prototype.slice.call(elems),
        within   = elemList.indexOf(elem),
        touching = [];
    if (within !== -1) {
        elemList.splice(within, 1);
    }
    for (var i = 0; i < elemList.length; i++) {
        if (detectOverlap(elem, elemList[i])) {
            touching.push(elemList[i].id);
        }
    }
    if (touching.length) {
        console.log(elem.id + ' touches ' + touching.join(' and ') + '.');
        alert(elem.id + ' touches ' + touching.join(' and ') + '.');
    } else {
        console.log(elem.id + ' touches nothing.');
        alert(elem.id + ' touches nothing.');
    }

}
#box1 {
    background-color: LightSeaGreen;
}
#box2 {
    top: 25px;
    left: -25px;
    background-color: SandyBrown;
}
#box3 {
    left: -50px;
    background-color: SkyBlue;
}
#box4 {
    background-color: SlateGray;
}
.box {
    position: relative;
    display: inline-block;
    width: 100px;
    height: 100px;
    color: White;
    font: bold 72px sans-serif;
    line-height: 100px;
    text-align: center;
    cursor: pointer;
}
.box:hover {
    color: Black;
}
<p>Click a box to see which other boxes are detected as touching it.<br />
<em>If no alert dialog box appears, open your console to view messages.</em></p>
<div class="box" id="box1">1</div>
<div class="box" id="box2">2</div>
<div class="box" id="box3">3</div>
<div class="box" id="box4">4</div>
gfullam
  • 11,531
  • 5
  • 50
  • 64
  • 1
    Yes. See [this example with 99 overlapping boxes](http://jsfiddle.net/gfullam/3w4f6msf/) Though at some point you'd likely start to see a noticeable performance dip as this solution cycles through all selected elements (all with `class="box"` in this case), gets each's position and compares it to the target element. – gfullam May 06 '15 at 15:18
  • 1
    You can tighten up this code even more by using `Math.min(p1, p2)` in `comparePostions()`. – MarsAtomic Nov 19 '18 at 03:33
  • @MarsAtomic That's a good thought, but in this case it appears ineffective because I want to compare just the first index of p1 & p2, then assign the entire array to r1 & r2; so I think the ternary is the best option. – gfullam Nov 19 '18 at 13:30
  • Isn't this the exact same comparison? I am not sure what the difference is between r1 and r2? r1 = p1[0] < p2[0] ? p1 : p2; r2 = p1[0] < p2[0] ? p2 : p1; – Jesse James Burton Jan 24 '19 at 20:42
  • 1
    @JesseJamesBurton The comparison is the same, but the assignment is different. I could store the result of the comparison and use that in the ternary of each expression to prevent redundant operations. – gfullam Jan 25 '19 at 15:39
  • UPDATE: Now using a single `if` statement within `comparePositions()` to avoid redundant ternary operations. – gfullam Jan 25 '19 at 15:50
  • 1
    Ah ok I see, so basically for each comparison you will always be assigning 1 of the items to r1 and one to r2 then correct? Thank you for the clarification! – Jesse James Burton Jan 25 '19 at 15:50
  • @JesseJamesBurton Yes. – gfullam Jan 25 '19 at 15:51
  • 1
    Awesome! That makes total sense :) – Jesse James Burton Jan 25 '19 at 15:51
1

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() and document.elementFromPoint()

  1. You can use element.getClientBoundingRect() (src) to get the position of the target (clicked, dragged, etc.) element.

  2. 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;
}
<div class="box" id="box1"></div>
<div class="box clickable" id="box2"></div>
<div class="box clickable" id="box3"></div>
gfullam
  • 11,531
  • 5
  • 50
  • 64