Skip to main content

How to Check if Two HTML Elements Overlap in JavaScript

Detecting when two elements on a webpage overlap is a fundamental requirement for building interactive user experiences, such as drag-and-drop interfaces, games, or guided tours. The standard method for this is to get the position and dimensions of each element relative to the viewport and then compare their boundaries.

This guide will teach you how to use the getBoundingClientRect() method to get an element's coordinates and how to implement a reusable function to accurately determine if two elements are overlapping.

Core Method: Element.getBoundingClientRect()

The element.getBoundingClientRect() method is the key to this solution. It returns a DOMRect object, which provides information about the size and position of an element relative to the viewport.

The returned object includes the following properties:

  • top: The distance from the top of the viewport to the top edge of the element.
  • right: The distance from the left of the viewport to the right edge of the element.
  • bottom: The distance from the top of the viewport to the bottom edge of the element.
  • left: The distance from the left of the viewport to the left edge of the element.
  • width and height: The dimensions of the element.

Problem: given two elements on a page, how can we determine if their rectangular boundaries are currently intersecting?

<div id="box1" class="box salmon">Box 1</div>
<div id="box2" class="box lime">Box 2</div>
const box1 = document.getElementById('box1');
const box2 = document.getElementById('box2');

const rect1 = box1.getBoundingClientRect();
const rect2 = box2.getBoundingClientRect();

console.log('Box 1 Rect:', rect1);
console.log('Box 2 Rect:', rect2);

The Overlap Detection Logic Explained

It is often easier to first define the conditions under which two rectangles do not overlap. Two rectangles, A and B, do not overlap if any of the following four conditions are true:

  1. A is entirely to the left of B. (A.right < B.left)
  2. A is entirely to the right of B. (A.left > B.right)
  3. A is entirely above B. (A.bottom < B.top)
  4. A is entirely below B. (A.top > B.bottom)

If none of these conditions are true, the rectangles must be overlapping. Therefore, the logic for an overlap is simply the negation of all four non-overlap conditions combined.

Solution (in pseudocode):

overlap = !( A.right < B.left OR A.left > B.right OR A.bottom < B.top OR A.top > B.bottom )

Creating a Reusable elementsOverlap() Function

We can encapsulate this logic in a clean, reusable function that takes two DOM elements as arguments.

Solution:

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
);
}

// Example HTML Setup
// <div id="box1" style="position: absolute; top: 50px; left: 50px; ..."></div>
// <div id="box2" style="position: absolute; top: 100px; left: 100px; ..."></div>
// <div id="box3" style="position: absolute; top: 300px; left: 300px; ..."></div>

const el1 = document.getElementById('box1');
const el2 = document.getElementById('box2'); // Overlaps with box1
const el3 = document.getElementById('box3'); // Does not overlap

console.log('box1 and box2 overlap:', elementsOverlap(el1, el2)); // Output: true
console.log('box1 and box3 overlap:', elementsOverlap(el1, el3)); // Output: false

Practical Example: A Simple Drag-and-Drop Target

A perfect use case for overlap detection is a drag-and-drop interface. This script allows a user to drag an element. When the dragged element overlaps a "drop zone," the drop zone changes color to give the user visual feedback.

<div id="draggable" class="box salmon">Drag Me</div>
<div id="dropzone" class="box lime">Drop Zone</div>
const draggable = document.getElementById('draggable');
const dropzone = document.getElementById('dropzone');

// Make the draggable element move with the mouse
let isDragging = false;
draggable.addEventListener('mousedown', () => { isDragging = true; });
document.addEventListener('mouseup', () => { isDragging = false; });

document.addEventListener('mousemove', (event) => {
if (!isDragging) return;

// Move the draggable element
draggable.style.left = event.clientX - (draggable.offsetWidth / 2) + 'px';
draggable.style.top = event.clientY - (draggable.offsetHeight / 2) + 'px';

// Check for overlap while moving
if (elementsOverlap(draggable, dropzone)) {
dropzone.style.backgroundColor = 'gold'; // Highlight drop zone
} else {
dropzone.style.backgroundColor = 'lime'; // Revert to original color
}
});

// (Helper function from above)
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
);
}

Conclusion

Detecting when two elements overlap is a straightforward process in JavaScript using the getBoundingClientRect() method.

  • The core of the solution is to get the rectangular boundaries of both elements.
  • The most reliable logic is to check for the four conditions under which the elements do not overlap.
  • If none of those non-overlapping conditions are met, the elements must be intersecting.
  • Encapsulating this logic in a reusable function like elementsOverlap(el1, el2) is a best practice.

This technique is fundamental for creating rich, interactive web applications with features like drag-and-drop, collision detection, and spatial awareness.