
Position Calculator is a JavaScript library for positioning tooltips, popovers, dropdowns, and other floating elements relative to a target.
It calculates movement offsets and adjusts placement near the edges of a viewport or container. You can then apply the results to the CSS or animations in your own UI.
Features
- Aligns reference points independently along the horizontal and vertical axes.
- Accepts pixel and percentage offsets for custom spacing.
- Flips the placement and shifts elements away from overflowing edges.
- Positions elements relative to mouse and pointer events.
- Measures overflow at an element’s current position.
How to Use It
Installation
Load the IIFE browser build in a standards-mode HTML document (<!doctype html>):
<script src="https://cdn.jsdelivr.net/npm/@tlindig/position-calculator@2/dist/position-calculator.iife.min.js"></script>
For npm projects:
npm install @tlindig/position-calculator
import { PositionCalculator } from "@tlindig/position-calculator";
Basic Usage
Create a popover anchored to a button inside a card. Use the card as the collision boundary.
<div id="stage">
<button type="button" id="anchor"
aria-controls="panel" aria-expanded="false">
Upload status
</button>
<div id="panel" hidden>Upload complete</div>
</div>
Place the button near the bottom of the card. Give the popover an absolute position with initial numeric left and top values.
#stage {
position: relative;
height: 180px;
border: 1px solid #aaa;
}
#anchor {
position: absolute;
right: 12px;
bottom: 12px;
}
#panel {
position: absolute;
left: 0;
top: 0;
width: max-content;
max-width: 100%;
box-sizing: border-box;
padding: 8px 12px;
background: #222;
color: #fff;
border-radius: 6px;
}
Add the returned moveBy.x and moveBy.y offsets to its current left and top values, respectively.
const stage = document.querySelector("#stage");
const button = document.querySelector("#anchor");
const panel = document.querySelector("#panel");
let calculator;
function applyPosition(result) {
if (!result) return;
const { left, top } = getComputedStyle(panel);
panel.style.left = parseFloat(left) + result.moveBy.x + "px";
panel.style.top = parseFloat(top) + result.moveBy.y + "px";
}
button.addEventListener("click", () => {
panel.hidden = !panel.hidden;
button.setAttribute("aria-expanded", String(!panel.hidden));
if (panel.hidden) return;
calculator = new PositionCalculator({
item: panel,
target: button,
boundary: stage,
itemAt: "top center",
targetAt: "bottom center",
targetOffset: { x: 0, y: 8, mirror: true },
flip: "both",
stick: "all"
});
applyPosition(calculator.calculate());
});
Update the Position When the Card Resizes
Use a ResizeObserver to recalculate the open popover whenever the panel, button, or card changes size.
const observer = new ResizeObserver(() => {
if (!panel.hidden && calculator) {
applyPosition(calculator.resize().calculate());
}
});
observer.observe(stage);
observer.observe(button);
observer.observe(panel);
Position Relative to the Pointer
A context menu or cursor-following popover needs a new calculator for each pointer position. Pass the event as the target. For touch input, use pointer events such as pointerdown or pointermove.
Add this handler to reposition the popover on a right-click inside the card:
stage.addEventListener("contextmenu", event => {
event.preventDefault();
panel.hidden = false;
button.setAttribute("aria-expanded", "true");
calculator = new PositionCalculator({
item: panel,
target: event,
boundary: stage,
targetOffset: { x: 12, y: 12, mirror: true },
flip: "both",
stick: "all"
});
applyPosition(calculator.calculate());
});
Detect Element Overflow
With the popover open, omit the target to check whether the panel fits entirely inside the card. Use the same check to find items that fit within a scroll container’s viewport.
const monitor = new PositionCalculator({
item: panel,
boundary: stage
});
const fitsInside = monitor.calculate()?.distance?.overflow === null;
All Configuration Options
item(ElementInput | null): The element to position. Accepts a DOM element, CSS selector, or array-like collection such as a NodeList or jQuery object (first element). Default:null.target(TargetInput | null): The positioning anchor. Accepts the same element inputs asitem, a window or document object,"window","document", or a mouse or pointer event withpageXandpageY. Default:nullfor overflow detection or sticking alone.boundary(BoundaryInput | null): The area used for collision detection. Accepts element inputs, window or document objects,"window", or"document". Both window and document boundaries use the current page viewport. Default:window. Set tonullto disable collision detection, flipping, and sticking.itemAt(At): The reference point on the item. Specify a vertical value (top,middle,bottom) followed by a horizontal value (left,center,right). Missing or invalid values fall back totoporlefton the corresponding axis. Default:"top left".targetAt(At): The reference point on the target. Uses the same placement keywords asitemAt. Default:"top left".itemOffset(Offset): Shifts the item relative to the aligned reference point. Default:{ y: 0, x: 0, mirror: true }.targetOffset(Offset): Shifts the reference point on the target. Default:{ y: 0, x: 0, mirror: true }.flip(Flip): Tries an opposite placement along an overflowing axis and selects the placement with less overflow. Requires a target. Accepts"item"to flip the item reference point,"target"to flip the target reference point,"both"ortrueto flip both, and"none"orfalseto disable flipping. Default:"none".stick(Stick): Shifts the item away from overflowing boundary edges after any flip. Accepts"all"ortruefor all edges,"none"orfalseto disable sticking, or one to four space-separated edge names (top,right,bottom,left). Works with or without a target. Default:"none".
API Methods
// Calculate placement with the configured flip and stick behavior.
// Reads current positions and scroll offsets; returns CalculationResult
// or null if the item was not found.
calculator.calculate();
// Remeasure positions and dimensions of item, target, and boundary.
// Returns the instance for chaining. Throws TypeError if the item is missing.
calculator.resize();
// Test a placement using stored measurements, without flip or stick.
// Returns CalculationResult. Refresh measurements first if elements moved.
calculator.calcVariant(
{ x: "center", y: "bottom" },
{ x: "center", y: "top" }
);
Calculation Result
Both methods return the same CalculationResult structure when a calculation succeeds. With calculate(), the distances reflect any flip and stick adjustments.
| Property | Description |
|---|---|
moveBy | Object containing x (horizontal) and y (vertical) movement in pixels from the item’s current position. Both are zero when the target is absent and sticking is disabled. |
distance | A Distance object with edge distances and overflow information, or null when there is no boundary. |
distance.top, distance.left | Distances in pixels. Positive values indicate overflow on those edges. |
distance.bottom, distance.right | Distances in pixels. Negative values indicate overflow on those edges. |
distance.overflow | An array of Edge values (for example, ["top", "left"]), or null if all edges fit. |
itemAt | The reference point used on the item as a placement string, or null without a target. |
targetAt | The reference point used on the target as a placement string, or null without a target. |
Alternatives
- Fast & Versatile Positioning Library – Floating UI
- Tiny Positioning Engine In JavaScript – nanopop
- Lightweight JS Tooltip Library with Smart Positioning – easy-tooltips







