Menu Close

How to Detect Two Elements Colliding or Overlapping in jQuery

jquery-collision

If you want to know when two elements overlap or collide with each other, then this may be of use to you. This option doesn’t require any plugins which I feel is the better option.

Below is a very simple way to detect collision between DOM elements. This can be coupled with a window resize function $( window ).resize(function(){}); to allow for continuous detection.

HTML:

<div id="one">One</div>
 <div id="two">Two</div>
 <span id="result"></span> 

CSS:

div {
    width:100%;
    height:500px;
    background:#EEE;
}
#two {
    position:absolute;
    left:200px;
    top:50px;
    background:#000;
} 

JavaScript:

console.log(isOverlap("#one","#two"));//true
console.log(isOverlap("#one","#three"));//false

var overlap = isOverlap("#one","#two");

if (overlap) {
 // Do something when elements are overlapping
} else {
 // Do something when elements are not overlapping
} 

jQuery:

$("#result").text(isOverlap("#one","#two")+","+isOverlap("#one","#three")+","+isOverlap("#two","#three"));

function isOverlap(idOne,idTwo){
        var objOne=$(idOne),
            objTwo=$(idTwo),
            offsetOne = objOne.offset(),
            offsetTwo = objTwo.offset(),
            topOne=offsetOne.top,
            topTwo=offsetTwo.top,
            leftOne=offsetOne.left,
            leftTwo=offsetTwo.left,
            widthOne = objOne.width(),
            widthTwo = objTwo.width(),
            heightOne = objOne.height(),
            heightTwo = objTwo.height();
        var leftTop = leftTwo &gt; leftOne &amp;&amp; leftTwo  topOne &amp;&amp; topTwo  leftOne &amp;&amp; leftTwo+widthTwo  topOne &amp;&amp; topTwo  leftOne &amp;&amp; leftTwo  topOne &amp;&amp; topTwo+heightTwo  leftOne &amp;&amp; leftTwo+widthTwo  topOne &amp;&amp; topTwo+heightTwo &lt; topOne+heightOne;
        return leftTop || rightTop || leftBottom || rightBottom;
} 
Posted in HTML, JavaScript, jQuery, Web Technologies

You can also read...