PDA

View Full Version : Can I detect when a DIV overlaps another DIV?



aaron1a12
07-01-2010, 08:02 PM
Can I detect when a DIV overlaps another DIV? You see, I'm animating a simple DIV but I want it to collide (or simply to fire up a function) when the DIV overlaps another DIV.

Is this possible with JavaScript and Only Javascript?

The results I need are similar to this:
http://www.java2s.com/Code/JavaScriptDemo/DynAPIExamplesDragDropwCollisionDetection.htm

djr33
07-01-2010, 10:19 PM
Its certainly possible but the math would be complex and possibly a lot to process so it might run slowly on some computers.

You could create a function like overlaps(div1,div2) and that would be easy to use but the math inside it is complex. Start with a library like jquery and get coordinates on the page. Then compare top left and bottom right corners of each div. If you find that any corner of div2 is between those of div1 or that both are outside the correct relative corners then you know it is overlapping.

Finally you can put this in a loop that continuously checks if you need that but that's where it gets resource-intensive.

aaron1a12
07-02-2010, 11:49 PM
It doesn't matter if it runs slowly on old computers since it's going to be something private. But you say "Start with a library like jquery", I can't use jquery because I don't know how to combine it then with a custom javascript function.

?????

djr33
07-03-2010, 12:22 AM
You don't need jquery, but it will just make things faster.

Jquery is designed to shortcuts common processes. In this case, it'll help with selecting elements on the page and finding their positions.

Jquery doesn't work by itself and the whole point is combining it to make advanced coding easier.