How can I see if an element is touching another in JavaScript? I am a beginner so I was looking for something simple that doesn't require a lot of coding.
Asked
Active
Viewed 135 times
-2
-
This should help you - https://stackoverflow.com/questions/29916874/can-you-tell-if-one-element-is-touching-another-using-javascript – CodeWalker May 29 '21 at 07:31
1 Answers
2
Have a look at Element.getBoundingClientRect()
which will give you a bounding box including x
, y
, width
, height
, …. If it's rectangular elements, then you can simply check if they intersect.

qqilihq
- 10,794
- 7
- 48
- 89
-
But how can i use Element.getBoundingClientRect() to see if 2 divs (1 of them is draggable) is touching the other one. Im just a begginer so idk how to use js that well. – Lirik Rexhepi May 29 '21 at 08:00
-
@LirikRexhepi Using math. You have `top`, `right`, `bottom`, and `left` properties available as well. – Sebastian Simon May 29 '21 at 08:26