Intersect2D
by Michael Prosser
HTML
<div id="container">
<div id="box1"></div>
<div id="box2"></div>
</div>
CSS
#container {
width:600px;
height:400px;
position:relative;
background-color:#ebebeb;
}
#box1 {
background-color:#333333;
width:20px;
height:20px;
position:absolute;
left:100px;
top:100px;
}
#box2 {
background-color:#666666;
width:20px;
height:20px;
position:absolute;
left:200px;
top:200px;
}
JavaScript
function intersect2D(a, b) {
return (a.left <= b.right &&
b.left <= a.right &&
a.top <= b.bottom &&
b.top <= a.bottom)
}
$(document).ready(function(){
$selector1 = $('#box1');
$selector2 = $('#box2');
$selector1.draggable({
drag: function( event, ui ) {
var a = { left: parseInt($selector1.css('left')), right: parseInt(parseInt($selector1.css('left')) + $selector1.width()), top: parseInt($selector1.css('top')), bottom: parseInt(parseInt($selector1.css('top')) + $selector1.height()) };
var b = { left: parseInt($selector2.css('left')), right: parseInt(parseInt($selector2.css('left')) + $selector2.width()), top: parseInt($selector2.css('top')), bottom: parseInt(parseInt($selector2.css('top')) + $selector2.height()) };
if(intersect2D(a, b)){
alert("HIT");
}
}
});
});