Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMSSQLMySQLPHPSilvaTechnologiesWordpress
Silva Web Designs - Blog

How to detect two elements colliding or overlapping in jQuery

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.

CSS


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

HTML


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

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 > leftOne && leftTwo < leftOne+widthOne                  && topTwo > topOne && topTwo < topOne+heightOne,             rightTop = leftTwo+widthTwo > leftOne && leftTwo+widthTwo < leftOne+widthOne                  && topTwo > topOne && topTwo < topOne+heightOne,             leftBottom = leftTwo > leftOne && leftTwo < leftOne+widthOne                  && topTwo+heightTwo > topOne && topTwo+heightTwo < topOne+heightOne,             rightBottom = leftTwo+widthTwo > leftOne && leftTwo+widthTwo < leftOne+widthOne                  && topTwo+heightTwo > topOne && topTwo+heightTwo < topOne+heightOne;
        return leftTop || rightTop || leftBottom || rightBottom;
}
Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

3 thoughts on “How to detect two elements colliding or overlapping in jQuery

Join the discussion