Skip to content

Instantly share code, notes, and snippets.

@wanybae
Created January 27, 2016 06:13
Show Gist options
  • Save wanybae/ec9474e1fe86531a0e7b to your computer and use it in GitHub Desktop.
Save wanybae/ec9474e1fe86531a0e7b to your computer and use it in GitHub Desktop.
How to detect if two <div> elements have collided
body {
padding: 10px;
color: #eee;
font-family: Arial;
}
h1 {
font-size: 24px;
margin-bottom: 20px;
}
#area {
border: 1px solid gray;
width: 500px;
height: 400px;
position: relative;
}
#area > div {
background-color: rgba(122, 122, 122, 0.3);
position: absolute;
text-align: center;
font-size: 50px;
width: 60px;
height: 60px;
}
#box0 {
background-color: rgba(255, 0, 0, 0.5) !important;
top: 150px;
left: 150px;
}
#box1 {
top: 260px;
left: 50px;
}
#box2 {
top: 110px;
left: 160px;
}
#box3 {
top: 200px;
left: 200px;
}
#box4 {
top: 50px;
left: 400px;
}
p {
margin: 5px 0;
}
<h1>Detect overlapping with JavaScript(jQuery)</h1>
<div id="area">
<div id="box0"></div>
<div id="box1">1</div>
<div id="box2">2</div>
<div id="box3">3</div>
<div id="box4">4</div>
</div>
// Usage : overlaps( sourceObject, targetObject );
overlaps = (function () {
function getPositions( el ) {
var pos, width, height;
pos = $( el ).position();
width = $( el ).width();
height = $( el ).height();
return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
}
function comparePositions( p1, p2 ) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : 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] );
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment