Constructor and options

Create an instance and set its options.

The constructor creates an instance that positions an item against a target. It reads the sizes of the elements once, so call resize() when they change.

Syntax

new PositionCalculator(options)

The call also works without new. It returns an instance in both cases.

Parameters

options is an object. Every key is optional, but item is needed to position anything.

Option Accepts Default
item element, selector string, or array-like collection (first element is used) null
target element, selector string, "window", "document", or a mouse or pointer event null, no target
boundary element, selector string, "window", "document", or null the window. null means no boundary
itemAt reference point string, for example "bottom center" "top left"
targetAt reference point string "top left"
itemOffset { y, x, mirror }, pixels or percentage strings { y: 0, x: 0, mirror: true }
targetOffset { y, x, mirror }, pixels or percentage strings { y: 0, x: 0, mirror: true }
flip "none", "item", "target", "both", or a boolean (true means "both") "none"
stick "none", "all", a boolean, or one to four edges separated by spaces "none"

The reference points, offsets, flip and stick are explained in the placement and collisions guide. Options you leave out keep their defaults. The instance keeps the merged options in its options property.

Return value

A PositionCalculator instance. Its methods are described on the methods page.

Exceptions

A missing item does not throw. The instance is created, and calculate() returns null. This happens for a selector that matches nothing, and for item: null.

A value of the wrong type throws a TypeError while the instance is created. The number 42 as item or target, and a number as itemAt, are examples. The message is not part of the API.

Example

const calculator = new PositionCalculator({
    item: "#tooltip",
    target: "#button",
    itemAt: "bottom center",
    targetAt: "top center",
    itemOffset: { y: -8, x: 0, mirror: true },
});

const { moveBy } = calculator.calculate();

The item and the target are looked up once, when the instance is created. If you replace them in the DOM, create a new instance.

Notes

See also