Possible Duplicate:
jQuery/Javascript collision detection
What would be the best way using preferably using $.position
to check if a <div>
is being touched or overlapped by another <div>
?
Thanks!
Possible Duplicate:
jQuery/Javascript collision detection
What would be the best way using preferably using $.position
to check if a <div>
is being touched or overlapped by another <div>
?
Thanks!
Here's a function I wrote a while back that does this:
var percentCovered = function (dim1, dim2) {
// The whole thing is covering the whole other thing
if (
(dim1.left <= dim2.left) &&
(dim1.top <= dim2.top) &&
((dim1.left + dim1.width) >= (dim2.left + dim2.width)) &&
((dim1.top + dim1.height) > (dim2.top + dim2.height))
) {
return 100;
}
// Only parts may be covered, calculate percentage
else {
dim1.right = dim1.left + dim1.width;
dim1.bottom = dim1.top + dim1.height;
dim2.right = dim2.left + dim2.width;
dim2.bottom = dim2.top + dim2.height;
var l = Math.max(dim1.left, dim2.left);
var r = Math.min(dim1.right, dim2.right);
var t = Math.max(dim1.top, dim2.top);
var b = Math.min(dim1.bottom, dim2.bottom);
if (b >= t && r >= l) {
/* $('<div/>').appendTo(document.body).css({
background: 'red',
position: 'absolute',
left: l + 'px',
top: t + 'px',
width: (r - l) + 'px',
height: (b - t) + 'px',
zIndex: 100
}); */
var percent = (((r - l) * (b - t)) / (dim2.width * dim2.height)) * 100;
// alert(percent + '% covered')
return percent;
}
}
// Nothing covered, return 0
return 0;
};
It takes as arguments two objects each containing width, height, left and top properties. Like this:
var el1 = $('#el-1');
var el2 = $('#el-1');
var offset1 = el1.offset();
var offset2 = el2.offset();
var dim1 = {
width: el1.outerWidth(),
height: el1.outerHeight(),
left: offset1.left,
top: offset1.top
};
var dim2 = {
width: el2.outerWidth(),
height: el2.outerHeight(),
left: offset2.left,
top: offset2.top
};
alert(percentCovered(dim1, dim2));
I guess you could move that offset stuff to the function if you don't mind it being calculated every time you call it.