Search code examples
javascripthtmldomcss-positionoverlapping

How to programmatically tell if two absolutely positioned elements overlap?


I don't think there's any such method in the DOM API like element.doesOverlap(otherElement), so I think I have to calculate this by hand, right? Not sure if there are any shortcuts.

If not, what is the method for this? It seems like there's so many ways something could overlap....it would be so many conditionals. Is there a concise way of writing this?

In pseudo code, I have this:

if (
  ((A.top < B.bottom && A.top >= B.top)
    || (A.bottom > B.top && A.bottom <= B.bottom))

    &&

    ((A.left < B.right && A.left >= B.left)
    || (A.right > B.left && A.right <= B.right))) {
  // elements A and B do overlap
}

^Is this the simplest way?


Solution

  • There isn't an easier way. The correct code is this, covering all possible ways two elements can overlap:

    const doElementsOverlap = (elementA: any, elementB: any) => {
      const A = elementA.getBoundingClientRect();
      const B = elementB.getBoundingClientRect();
      return (
        ((A.top < B.bottom && A.top >= B.top)
        || (A.bottom > B.top && A.bottom <= B.bottom)
        || (A.bottom >= B.bottom && A.top <= B.top))
    
        &&
    
        ((A.left < B.right && A.left >= B.left)
        || (A.right > B.left && A.right <= B.right)
        || (A.left < B.left && A.right > B.right))
      );
    };