Check if a given DOMRect is contained within another DOMRect
True when the target lies inside the container or on its edges.
function isContained({ target, container }) { return target.x >= container.x && target.x + target.width <= container.x + container.width && target.y >= container.y && target.y + target.height <= container.y + container.height; }
Input & expected output
Input
{
"target": {
"x": 10,
"y": 10,
"width": 20,
"height": 20
},
"container": {
"x": 0,
"y": 0,
"width": 40,
"height": 40
}
}Expected output
trueThe edge case
Input
{
"target": {
"x": 30,
"y": 10,
"width": 20,
"height": 20
},
"container": {
"x": 0,
"y": 0,
"width": 40,
"height": 40
}
}Expected output
falseKnow the limits
- Pass rects from getBoundingClientRect() or plain { x, y, width, height } objects. The original read left and top, which plain objects lack.
- Assumes non-negative width and height, as getBoundingClientRect() returns. Shared edges count as contained.
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 a given DOMRect is contained within another DOMRect from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Reads x and y, which DOMRects and plain JSON rects share, instead of left and top; runs in the lab. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Check if two DOMRects intersect — Two rects intersect when they meet on both axes.
- 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.