2

So I was wondering if you could test for two elements touching each other running a if statement. I know that I am new to javascript and I do not know as much as others, but I couldn't find out how to test for two elements touching.

For example I would want it to be something like this:

var el = document.getElementById("element1");
var el2 = document.getElementById("element2");

if (el1 touching el2) {
//code
//code
}

Yes I know this is not how you do it but I would like to know if there was a certain way you could tell if two elements are touching...

zero298
  • 25,467
  • 10
  • 75
  • 100
Henry Redder
  • 27
  • 1
  • 11
  • 1
    Yes, this is rather complicated to do, but it is possible. Now all that is left is to do it :D Good luck. – Travis J May 26 '16 at 23:56
  • 2
    Define "touch" term first. – c-smile May 26 '16 at 23:58
  • yeah I am wondering how I should do this? – Henry Redder May 26 '16 at 23:59
  • 1
    Start with [getBoundingClientRect()](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) probably. And consider if you want to take z-index into account. Since they are both boxes, you could probably use [AABB](http://stackoverflow.com/questions/22512319/what-is-aabb-collision-detection) collision detection to see if they are intersecting. – zero298 May 26 '16 at 23:59

1 Answers1

2

Use Element.getBoundingClientRect() to get their boxes. Then use a collision test, such as AABB, to see if they are intersecting.

Note that I don't think this will work if you apply any crazy rotation transforms to either element.

Community
  • 1
  • 1
zero298
  • 25,467
  • 10
  • 75
  • 100