Having issues with collision detection on those 2 <div> tags of yours? Maybe you don’t want to use a plugin either? Well here’s a simple way to solve your issue.
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:200px; height:200px; background:#EEE; } #two{ position:absolute; left:100px; top:50px; background:#F60; }
HTML
<div id="one">One</div> <div id="two">Two</div> <div id="three">Three</div> <span id="result"></span>
JavaScript
console.log(isOverlap("#one","#two"));//true console.log(isOverlap("#one","#three"));//false console.log(isOverlap("#two","#three"));//true var overlap = isOverlap("#one","#two"); if (overlap) { // Do something when elements are overlapping } else { // Do something when elements are not overlapping }
// jQuery required $("#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; }
View More Tutorials
COMMENTS