Check if two Elements overlap using JavaScript

avatar

Borislav Hadzhiev

Tue Jan 11 20222 min read

Check if two Elements overlap using JavaScript #

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 in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box1" style="width: 100px; height: 100px; background-color: salmon; position:absolute;"> Box 1 </span> <div id="box2" style="width: 100px; height: 100px; background-color: lime"> Box 2 </span> <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.

index.js
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.

The 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.

If all of the conditions in the parenthesis are met, then the elements don't overlap and the function returns 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 element, it returned false, because the third element has a margin-top of 150px and does not overlap the first.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee