How to detect collision between two divs in jquery?
Snippet Code
Rate this page :
[ 0 votes]
Jquery collision is a simple example to check whether two div element have collided. If there was a collision then it shows true and if there is no collision it shows false. Here, function collision is used to detect the collision of two divisions.
<script type="text/javascript">
function collision(firstdiv, seconddiv) {
var pos_x1 = firstdiv.offset().left;
var pos_y1 = firstdiv.offset().top;
var h1 = firstdiv.outerHeight(true);
var w1 = firstdiv.outerWidth(true);
var b1 = pos_y1 + h1;
var r1 = pos_x1 + w1;
var pos_x2 = seconddiv.offset().left;
var pos_y2 = seconddiv.offset().top;
var h2 = seconddiv.outerHeight(true);
var w2 = seconddiv.outerWidth(true);
var b2 = pos_y2 + h2;
var r2 = pos_x2 + w2;
if (b1 < pos_y2 || pos_y1 > b2 || r1 < pos_x2 || pos_x1 > r2) return false;
return true;
}
window.setInterval(function() {
$('#result').text(collision($('#div1'), $('#div2')));
}, 200);
</script>
<style>
#div1 { width: 100px; height: 100px; background-color: red; }
#div2 { width: 100px; height: 100px; background-color: green; }
</style>
<div id='div1'>First Div</div>
<div id='div2'>Second Div</div>
<p>COLLISION DETECTION : <span id="result" style='font-weight:bold;'>false</span>