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;
}
This is the best simple example i have ever seem. It works like a charm!!
Thanks you guys.
There are a couple of cases, where your algorithm would not detect an overlap! One of those cases is, when the boxes overlap like a cross. Demonstrated in this fiddle:
https://jsfiddle.net/Simca/cmg9ot4e/7/
Best regards
Roman
I tried this at https://www.jmu.edu/university-communications/staff.shtml and it didn’t work when on an iPhone. One can see the title overflow to elements below.