Methods

Calculate a position, calculate one placement, or read the sizes again.

An instance has three methods. resize() returns the instance, so calls can be chained. calculate() and calcVariant() return a result object. No method moves the item: you apply moveBy yourself.

Method Returns Use it to
calculate() result object or null get the final position, with flip and stick applied
calcVariant() result object test one placement, for example whether it overflows
resize() the instance read sizes again after the item, target or boundary changed size

calculate()

Calculates how far the item has to move so that its reference point meets the reference point of the target. If the item then overflows the boundary, it applies flip and then stick.

Syntax

calculate(): CalculationResult | null

Parameters

None.

Return value

A result object, or null if the item was not found when the instance was created.

Description

Example

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

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

calcVariant()

Calculates the position for one given placement. It does not apply flip or stick. calculate() uses it internally.

Syntax

calcVariant(
    itemAt: { x: Horizontal; y: Vertical } | null,
    targetAt: { x: Horizontal; y: Vertical } | null,
): CalculationResult

Parameters

itemAt
Reference point on the item: an object with x ("left", "center" or "right") and y ("top", "middle" or "bottom").
targetAt
The same for the target.

Return value

A result object for exactly this placement. If one argument is null or the instance has no target, moveBy is { y: 0, x: 0 }, itemAt and targetAt are null, and distance describes the item where it is.

Description

Example

calculator.resize();
const below = calculator.calcVariant({ x: "left", y: "top" }, { x: "left", y: "bottom" });
const fitsBelow = below.distance?.overflow === null;

resize()

Reads the position and size of the item, the target and the boundary again.

Syntax

resize(): this

Parameters

None.

Return value

The instance, so you can write calculator.resize().calculate().

Exceptions

A TypeError if the item was not found when the instance was created. In that case calculate() returns null.

Description

Call it when the size of the item, the target or the boundary changed, for example after you set a new text in a tooltip. calculate() only refreshes positions.

Example

tooltip.textContent = "A longer text";
const result = calculator.resize().calculate();

See also