@modracx/tooltip-js
v1.0.0
Published
Lightweight tooltips and popovers for web pages — 12 placements with flip and shift collision handling, hover/focus/click/manual triggers, interactive popovers, delegation and full ARIA wiring. Zero dependencies.
Maintainers
Readme
@modracx/tooltip-js
Tooltips and popovers for the web. Twelve placements with flip-and-shift collision handling, hover/focus/click/manual triggers, interactive popovers, event delegation, and ARIA wired up properly. Zero dependencies, no build step.
npm install @modracx/tooltip-jsimport Tooltip from "@modracx/tooltip-js";
Tooltip.create(document.querySelector("#save"), {
content: "Saves without closing the editor",
placement: "top",
});Or with no JavaScript per element at all:
<button data-tooltip="Saves without closing the editor">Save</button>Contents
- Options
- The controller
- Placement and collisions
- Triggers
- Popovers
- Content
- Delegation
- Declarative setup
- Styling
- jQuery
- Granular API
- Accessibility
- Browser support
Options
Tooltip
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| content | string | Element | function | null | null | Falls back to the trigger's title. |
| html | boolean | false | Treat string content as HTML. |
| placement | string | "top" | A side, optionally -start / -end. |
| offset | number | 8 | Px from the trigger, arrow included. |
| padding | number | 8 | Minimum distance from the viewport edge. |
| flip | boolean | true | Swap to the opposite side when there is no room. |
| shift | boolean | true | Slide along the cross axis to stay on screen. |
| arrow | number | 8 | Arrow size in px. 0 removes it. |
| animation | number | 140 | Fade ms. |
| className | string | null | null | Extra class for your own styling. |
| unstyled | boolean | false | Drop the built-in look entirely. |
| maxWidth | number | 260 | Px before wrapping. |
| appendTo | Element | null | document.body | |
| role | "tooltip" | "dialog" | "tooltip" | "dialog" makes it a popover. |
| boundary | Element | null | null | Constrain to this box instead of the viewport. |
| zIndex | number | 2147482000 | |
Triggers
| Option | Type | Default | Notes |
| --- | --- | --- | --- |
| trigger | string | string[] | ["hover", "focus"] | hover, focus, click, manual. |
| delay | number | object | { show: 80, hide: 80 } | A number sets both. |
| interactive | boolean | false | Let the pointer move into the tooltip. |
| interactiveDebounce | number | 90 | Grace period to cross the gap, in ms. |
| closeOnEscape | boolean | true | |
| closeOnOutsideClick | boolean | true | Click triggers only. |
| hideOnScroll | boolean | false | Hide instead of following along. |
The controller
const t = Tooltip.create(el, { content: "Hello" });
t.show();
t.hide();
t.hide(true); // skip the fade
t.toggle();
t.setContent("Updated");
t.setPlacement("right");
t.update(); // re-measure after the trigger changed size
t.destroy(); // restores the trigger's attributes exactly
t.isVisible;
t.element; // null until first shown
t.id; // used for aria-describedby / aria-controlsEvents: show, hide, and position — the last one fires on every
placement pass with { x, y, side, align, flipped, arrow }.
t.on("position", ({ side, flipped }) => {
if (flipped) console.log("no room above, went", side);
});Placement and collisions
Twelve placements: each of top, bottom, left, right, optionally
suffixed -start, -center (the default) or -end.
Correction happens in a fixed order, and the order is what makes it stable:
- Flip. If the requested side overflows, try the opposite one — but only switch if it is genuinely roomier. Without that check, a tooltip taller than the viewport flaps between top and bottom on every reposition.
- Shift. Slide along the cross axis until it is inside the viewport,
respecting
padding. - Arrow. Point it at the trigger's centre, which after shifting is no longer the tooltip's centre, clamped so it never runs past the corners.
The tooltip is position: fixed on document.body, so no overflow: hidden
ancestor can clip it. It follows every scrollable ancestor and the window,
coalesced to one reposition per frame — and hides itself when the trigger
scrolls out of view, rather than floating over nothing.
boundary constrains it to an element's box instead of the viewport.
Triggers
Tooltip.create(el, { trigger: "hover" }); // pointer only
Tooltip.create(el, { trigger: ["hover", "focus"] }); // the default
Tooltip.create(el, { trigger: "click" }); // toggles
Tooltip.create(el, { trigger: "manual" }); // API onlyfocus shows with no delay — a keyboard user has already committed, so making
them wait is just latency. hover uses delay.show.
Touch is handled: a pointerenter from a touch pointer is ignored, because a
tap that opens a hover tooltip leaves it stuck with no way to dismiss it. Taps
toggle instead.
interactive: true keeps the tooltip open while the pointer is over it
rather than the trigger, with interactiveDebounce covering the gap between
the two. Without it, a tooltip containing a link is unusable.
Popovers
Tooltip.create(el, {
role: "dialog",
html: true,
content: "<strong>Heads up</strong><br>With a <a href='/docs'>link</a>.",
});role: "dialog" switches several defaults at once, because a panel of real
content wants different behaviour from a hint:
| | tooltip | popover |
| --- | --- | --- |
| ARIA | aria-describedby | aria-expanded + aria-controls |
| Trigger | hover + focus | click |
| Interactive | no | yes |
| Pointer events | none | auto |
Escape closes it and returns focus to the trigger.
Content
Resolved in this order:
- The
contentoption — a string, anElement, or a function called with the trigger and re-evaluated on every show. - The trigger's
titleattribute.
A title is moved off the element while the tooltip owns it (otherwise the
browser's own tooltip appears on top of yours) and restored by destroy().
A tooltip with nothing to say never renders — no empty box, and no element added to the DOM.
Tooltip.create(el, { content: (trigger) => `Last saved ${stamp(trigger)}` });html: true uses innerHTML. That is your markup, not user input — do not
pass unsanitised strings through it.
Delegation
For many triggers, one handler beats one instance each:
const stop = Tooltip.delegate(document.body, "[data-tip]", {
content: (el) => el.dataset.tip,
placement: "bottom",
});Instances are created on first hover or focus and reused after. Elements added
later are picked up automatically, with no re-scan. stop() removes the
handler and destroys everything it made.
Declarative setup
The standalone vanilla/ and jquery/ builds call autoInit(document) on
DOMContentLoaded:
<button data-tooltip="Plain text is the content">Save</button>
<button data-tooltip="On the right" data-tooltip-placement="right">Copy</button>
<button data-tooltip='{"content":"Configured","placement":"bottom","arrow":12}'>More</button>data-tooltip holding a plain string is the content; holding a JSON object
is the options. Individual data-tooltip-* attributes override either.
The npm package does not auto-run on import — call Tooltip.autoInit().
Styling
Three levels:
Tooltip.create(el, { className: "my-tip" }); // built-in look plus your class
Tooltip.create(el, { unstyled: true }); // positioning only, no stylingThe element carries data-side and data-align reflecting where it actually
ended up, so CSS can respond to a flip:
[data-tooltip-js][data-side="bottom"] { /* … */ }jQuery
import "@modracx/tooltip-js/jquery";
$("[data-tip]").Tooltip("create", { placement: "bottom" });
$("#save").Tooltip("show");
$("#save").Tooltip("setContent", "Saved");
$("#save").Tooltip("destroy");
$("#save").Tooltip("get"); // controller, or null
$("#save").Tooltip("isVisible"); // boolean$.Tooltip also exposes create, clear, get, autoInit and delegate
for callers that skip the plugin wrapper.
Granular API
import { createTooltip, attachTriggers, computePosition } from "@modracx/tooltip-js";
const t = createTooltip(el, { content: "Manual only" });
attachTriggers(t, { trigger: "click", delay: 0 });computePosition(anchorRect, tipSize, options) is the maths on its own — no
DOM, no side effects — if you want the placement logic for something else:
const { x, y, side, flipped } = computePosition(
el.getBoundingClientRect(),
{ width: 160, height: 32 },
{ placement: "top", offset: 8, arrowSize: 8 }
);Accessibility
- Tooltips are wired with
aria-describedbywhile visible and unwired on hide, preserving any ids that were already there rather than overwriting the attribute. - Popovers use
aria-expandedandaria-controlsinstead, which is what a disclosure actually needs. focusis a default trigger, so a tooltip is not mouse-only. It shows with no delay for keyboard users.- Escape closes, and a popover returns focus to its trigger.
- The native
titleis removed while ours is attached, so a screen reader and a sighted user are not given two competing descriptions — and it is put back ondestroy(). - Reduced motion removes the fade; nothing else changes.
One thing this library cannot fix for you: a tooltip on a non-focusable element
is invisible to keyboard users. Put them on buttons and links, or give the
trigger a tabindex.
Browser support
Chrome / Edge 88+, Firefox 78+, Safari 14+. Needs pointer events for hover and
matchMedia for reduced motion; both degrade rather than break.
Developer
Built by Kenneth D'silva — modracx.com
License
MIT © Kenneth D'silva (Modracx)
