Jack
Jack

Reputation: 327

JavaScript: Trigger a function when two divs touch / overlap

The title explains it really. How to do this? Both divs are of differing size. Both divs are moving (I'm making a little Jquery game). If one hits the other, I want stuff to happen.

Thanks

Upvotes: 1

Views: 2177

Answers (2)

TheHippo
TheHippo

Reputation: 63139

There is no JavaScript event for onOverlap, you have to do the calculation whether the divs are overlapping by youself:

var valueInRange = function(value,min, max) { 
   return (value >= min) && (value <= max);
}

var overlap = function(x1,y1,w1,h1,x2,y2,w2,h2) {
   xOverlap = valueInRange(x1, x2, x2 + w2) || valueInRange(x2, x1, x1 + w1);
   yOverlap = valueInRange(y1, y2, y2 + h2) || valueInRange(y2, y1, y1 + h1);
   return xOverlap && yOverlap;
}

Upvotes: 3

Andrzej Doyle
Andrzej Doyle

Reputation: 103797

How are you causing the divs to move? One way to do it, certainly, would be to write a simple boolean-returning function that, given two divs, works out whether they overlap (get the coordinates of the corners and just compare for an intersection). Then, at the end of the function that causes the divs to move, call this function and take appropriate action if so.

In fact depending on how you're doing the moving you may even have the coordinates of both divs available making this very efficient.

Beyond that I'm not aware of any "onoverlap" event or similar, so periodically checking is the only generally-applicable way I can think of. There may be a faster method available depending on how your code is structured.

Upvotes: 1

Related Questions