Getting started

Install the package, import it and place your first element.

Goal

Place a small tooltip below a button. At the end, the tooltip is centred under the button and touches it. The library calculates the offset. You move the element.

Before you start

Steps

1. Install

npm install @tlindig/position-calculator

2. Import

In an ES module, import the named export:

import { PositionCalculator } from "@tlindig/position-calculator";

Without a bundler, load the IIFE build from node_modules/@tlindig/position-calculator/dist/ with a script tag, file position-calculator.iife.min.js. It defines the global PositionCalculator.

3. Create the instance and calculate

The item must be positioned, for example with position: absolute, so that moveBy can be applied to its left and top. Give the item a target and the reference points:

const tooltip = document.querySelector("#tooltip");
const button = document.querySelector("#button");

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

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";

itemAt is the point of the item that meets targetAt, the point of the target. Both use the form "vertical horizontal". moveBy is the distance the item has to move, in pixels.

Try it

The code above is checked in a browser against the built IIFE file. The tooltip is centred under the button, its top edge is at the bottom edge of the button, and the horizontal centres match. Use the playground to change the placement and see the result.

Next

Coming from 1.x

Version 1 was a jQuery plugin. Version 2 is a standalone class that needs no jQuery. The options, the methods and the result object follow 1.x, and the test suite of the repository compares the results with the 1.1.3 code. These are the differences that can affect your code.

Package and loading

const { PositionCalculator } = require("@tlindig/position-calculator");

The package is an ES module. package.json declares engines.node as >=24, the only Node version the tests of this project run on.

Behavior

TypeScript types

The types page lists every declaration. Not checked here: Node versions other than 24, and bundlers or test runners other than the ones in npm run test:consumer of the repository.