Compare two DOMRects for size and position match
Compare x, y, width and height exactly.
function sameRect({ a, b }) { return ['x', 'y', 'width', 'height'].every(key => a[key] === b[key]); }
Input & expected output
Input
{
"a": {
"x": 0,
"y": 0,
"width": 100,
"height": 200
},
"b": {
"x": 0,
"y": 0,
"width": 100,
"height": 200
}
}Expected output
trueThe edge case
Input
{
"a": {
"x": 0,
"y": 0,
"width": 100,
"height": 200
},
"b": {
"x": 0,
"y": 0.5,
"width": 100,
"height": 200
}
}Expected output
falseKnow the limits
- Exact comparison. Layout coordinates are often fractional, as the edge case shows; compare rendered positions with a tolerance such as Math.abs(a - b) < 0.5.
- The original compared top and left, which plain objects lack.
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 Compare two DOMRects for size and position match from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Compares x and y instead of top and left so plain JSON rects work; 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.
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- Get the center point of a DOMRect — Return [x, y] of the rect’s center.