Check if two DOMRects intersect
Two rects intersect when they meet on both axes.
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
trueThe edge case
Input
{
"a": {
"x": 0,
"y": 0,
"width": 40,
"height": 40
},
"b": {
"x": 40,
"y": 0,
"width": 10,
"height": 10
}
}Expected output
trueKnow 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.
Keep exploring
- Check if a given DOMRect is contained within another DOMRect — True when the target lies inside the container or on its edges.
- Compare two DOMRects for size and position match — Compare x, y, width and height exactly.
- Get the center point of a DOMRect — Return [x, y] of the rect’s center.