Reputation: 517
How do I detect if two divs are overlapping?
Not taking into consideration the width of a div, it is basically a vertical line segment. The (top,left) point is point A while the bottom (top + height) is point B and so forth. I'd then compare each div to each to the other divs in the divs array and then create an array of colliding divs. However, I'm stuck on how to do this programmatically.
This is my array of divs:
var divs = [
{class:'A', top:0, left:0, height:'60px'},
{class:'B', top:50, left:60, height:'60px'},
{class:'C', top:30, left:10, height:'60px'},
{class:'D', top:100, left:180, height:'60px'},
{class:'E', top:80, left:50, height:'60px'},
{class:'F', top:110, left:200, height:'60px'},
{class:'G', top:55, left:80, height:'60px'}
];
Here's the function I had started:
this.collide = function( divs )
{
var collidingDivs = [], z = events.length;
for(i; i<z; i++)
{
if
(
// Begin pseudocode
( divsB.top >= divsA.top ) &&
( (divsB.top + divsB.height) <= (divsA.top + divsA.height) )
)
{
collidingDivs.push(divs[i].class);
}
}
console.log(collidingDivs); // Array of divs that overlap (collide)
};
I'm just utterly stuck at this point. How do I iterate over each div and check if it collides with any of the other divs?
Upvotes: 2
Views: 4505
Reputation: 56769
You need to loop through each div, and then compare with every other div in a nested loop. Then use logic like what you've written to compare each combination. Here is an example that simply prints out the overlapping divs to the output (note also that I changed the height
element to have a numerical value rather than text so that its value could be used in calculations):
var divs = [
{class:'A', top:0, left:0, height:60},
{class:'B', top:50, left:60, height:60},
{class:'C', top:30, left:10, height:60},
{class:'D', top:100, left:180, height:60},
{class:'E', top:80, left:50, height:60},
{class:'F', top:110, left:200, height:60},
{class:'G', top:55, left:80, height:60}
];
for (var i=0; i < divs.length - 1; i++)
for (var j=i+1; j < divs.length; j++)
{
var I=divs[i];
var J=divs[j];
if ( (I.top <= J.top && (I.top + I.height) >= J.top) ||
(J.top <= I.top && (J.top + J.height) >= I.top) )
document.writeln(
I.class + " collides with " + J.class + "<br />");
}
Output:
A collides with B
A collides with C
A collides with G
B collides with C
B collides with D
B collides with E
B collides with F
B collides with G
C collides with E
C collides with G
D collides with E
D collides with F
D collides with G
E collides with F
E collides with G
F collides with G
Sample working code: http://jsfiddle.net/QUrWM/
Upvotes: 4