Position Calculator

Calculates where an element has to go relative to another element or a pointer event, and keeps it inside a boundary. You apply the result yourself.

What it does

Position Calculator gives you dynamic values in JavaScript for position, collision and collision avoidance, for popups and the like. It is made for people who build their own styles and components. It hides the complexity and keeps the flexibility: it does one thing, and it does that thing very well.

You give PositionCalculator an item, usually a target and optionally a boundary. It measures them and returns how far the item has to move. It does not move anything itself.

Speed

The numbers are data, they come back synchronously, and the library writes nothing to the page in the normal path. In the benchmark scene of this repository (Chrome 157, one machine, one target per item), one calculation for 100 elements takes 0.80 ms when it only calculates and writes nothing. When the targets move and the results are written as a transform, it takes 1.17 ms if you calculate all items first and apply the results afterwards, and 3.17 ms if you calculate and apply one item after the other. At 500 elements the same two orders take 5.4 ms and 46.5 ms, so call calculate() for all items first.

These numbers say nothing about other browsers or other pages, and the other tools in the comparison do more, for example updates for scroll parents. Scene, limits, the other tools and a way to repeat the run are on Alternatives and comparison.

Quick start

Create an instance with an item and a target, then apply moveBy to the item. Both reference points use the form "vertical horizontal":

const calculator = new PositionCalculator({
    item: tooltip,
    target: button,
    itemAt: "top center",
    targetAt: "bottom center",
});
const { moveBy } = calculator.calculate();

The full steps, including the IIFE build and a check of the result, are in Getting started.

Where next