Check if two DOMRects intersect

Two rects intersect when they meet on both axes.

JavaScript Version 1.0.0 · MIT · .md

check-if-two-dom-rects-intersect.js
function intersect({ a, b }) { return b.x <= a.x + a.width && b.x + b.width >= a.x && b.y <= a.y + a.height && b.y + b.height >= a.y; }

Input & expected output

Input

{
  "a": {
    "x": 0,
    "y": 0,
    "width": 40,
    "height": 40
  },
  "b": {
    "x": 10,
    "y": 10,
    "width": 20,
    "height": 20
  }
}

Expected output

true

The edge case

Input

{
  "a": {
    "x": 0,
    "y": 0,
    "width": 40,
    "height": 40
  },
  "b": {
    "x": 40,
    "y": 0,
    "width": 10,
    "height": 10
  }
}

Expected output

true

Know the limits

  • Touching edges count as intersecting, as the edge case shows. For a strict overlap use < and >, as in Check if a rectangle overlaps another one.
  • Assumes non-negative width and height, as getBoundingClientRect() returns.

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Check if two DOMRects intersect from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.

Reads x, y, width and height so plain JSON rects work; inclusive edges documented; runs in the lab. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.