Result object

The object that calculate() and calcVariant() return.

The result object is what calculate() and calcVariant() return. It holds how far to move the item, the distance to the boundary, and the reference points that were used.

Syntax

{
    moveBy: { y: number, x: number },
    distance: { top: number, left: number, bottom: number, right: number, overflow: string[] | null } | null,
    itemAt: string | null,
    targetAt: string | null,
}

Properties

Property Meaning
moveBy Pixels the item has to move from its current position, as y and x. It is { y: 0, x: 0 } when there is no target.
distance Space between the item and the boundary, or null without a boundary. A positive top or left means the item starts beyond that edge. A negative bottom or right means the item extends beyond that edge.
distance.overflow Array of the edges the item overflows, for example ["top", "left"], or null if no edge overflows. It is never an empty array.
itemAt Reference point used on the item, in the form "vertical horizontal", for example "bottom center". null without a target.
targetAt Reference point used on the target, in the same form. null without a target.

Example

const tooltip = document.querySelector("#tooltip");
const calculator = new PositionCalculator({
    item: tooltip,
    target: "#button",
    boundary: "window",
    itemAt: "bottom center",
    targetAt: "top center",
    flip: "both",
});

const result = calculator.calculate();
const style = getComputedStyle(tooltip);
tooltip.style.left = parseFloat(style.left) + result.moveBy.x + "px";
tooltip.style.top = parseFloat(style.top) + result.moveBy.y + "px";

if (result.distance?.overflow) {
    console.log("still outside the window at:", result.distance.overflow);
}

Notes

See also