Last updated: Mar 5, 2024
Reading time·2 min
To check if two elements overlap, use the getBoundingClientRect()
method to
get an object containing information about the relative position to the viewport
of the elements.
Then, compare the boundary edges (top, right, bottom, left) of the two rectangles.
Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <meta charset="UTF-8" /> </head> <body> <div id="box1" style=" width: 100px; height: 100px; background-color: salmon; position: absolute; " > Box 1 </div> <div id="box2" style="width: 100px; height: 100px; background-color: lime" > Box 2 </div> <div id="box3" style=" width: 100px; height: 100px; background-color: plum; margin-top: 150px; " > Box 3 </div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
function elementsOverlap(el1, el2) { const domRect1 = el1.getBoundingClientRect(); const domRect2 = el2.getBoundingClientRect(); return !( domRect1.top > domRect2.bottom || domRect1.right < domRect2.left || domRect1.bottom < domRect2.top || domRect1.left > domRect2.right ); } const el1 = document.getElementById('box1'); const el2 = document.getElementById('box2'); const el3 = document.getElementById('box3'); console.log(elementsOverlap(el1, el2)); // 👉️ true console.log(elementsOverlap(el1, el3)); // 👉️ false
We created a reusable function that checks if two elements overlap and returns a boolean result:
true
if the elements overlap.false
if they don't.We used the getBoundingClientRect method to get an object that contains information about the element's relative position to the viewport.
top
, right
, bottom
and left
properties describe the position of the element relative to the top-left of the viewport.Note that the rectangle's boundary edges (top
, right
, bottom
and left
)
change their values when the scrolling position changes because their values are
relative to the viewport.
false
.On the other hand, if all of the conditions return false
, then the elements
overlap.
When we invoked the elementsOverlap
function with the elements with ids box1
and box2
, the function returned true
because the first element has a
position set to absolute
and overlaps with the second.
When we invoked the function with the first and third elements, it returned
false
because the third element has a margin-top
of 150px
and does not
overlap the first.
You can learn more about the related topics by checking out the following tutorials: