DOM Align
dom-align is a JavaScript library designed for flexible and precise alignment of HTML DOM elements. It enables positioning a 'source' element relative to a 'target' element, supporting various alignment points (e.g., top-left, center, bottom-right), pixel-based offsets, and percentage-based offsets relative to the element's dimensions. A key feature is its ability to automatically adjust the source element's position if it overflows the viewport or specified boundaries, ensuring visibility. It provides robust cross-browser support, compatible with modern browsers like Chrome and Firefox, as well as older versions like Internet Explorer 9+. The current stable version is 1.12.4. While it does not adhere to a strict time-based release cadence, updates are typically released as new features are added, existing issues are resolved, or performance improvements are implemented. The library ships with comprehensive TypeScript type definitions, facilitating its use in typed JavaScript and TypeScript projects.
Common errors
-
TypeError: domAlign is not a function
cause This error typically occurs when attempting to `require` or import `dom-align` in a CommonJS module context, but the default export is not handled correctly, or the module system is misconfigured for ESM.fixIf using CommonJS, try `const domAlign = require('dom-align').default;` or ensure your build system (e.g., Webpack, Rollup) correctly transpiles ESM imports. For ESM, ensure you use `import domAlign from 'dom-align';`. -
Cannot read properties of null (reading 'style') or similar 'Cannot read property X of undefined'
cause This error indicates that either the `source` or `target` HTMLElement passed to `domAlign` is `null` or `undefined`, meaning the element could not be found or was not rendered yet.fixEnsure that both `source` and `target` elements exist in the DOM and are valid `HTMLElement` instances before calling `domAlign`. Use `document.getElementById()`, `document.querySelector()`, or a React/Vue ref to reliably get the elements after they are mounted.
Warnings
- gotcha The `sourceNode` must be absolutely positioned and initially placed off-screen (e.g., `left: -9999px; top: -9999px;`) for `dom-align` to calculate its dimensions correctly before applying the alignment, especially when dealing with dynamic content or initial rendering.
- gotcha When using percentage values in `offset` or `targetOffset`, they are calculated relative to the *sourceNode's* or *targetNode's* dimensions, respectively. Incorrect assumptions about their reference frame can lead to unexpected positioning.
- gotcha The `overflow` property's `adjustX` and `adjustY` flags determine if `dom-align` should automatically reposition the source node if it extends beyond the visible viewport. If these are not set to `true`, the source node might be clipped or hidden without adjustment.
Install
-
npm install dom-align -
yarn add dom-align -
pnpm add dom-align
Imports
- domAlign
const domAlign = require('dom-align');import domAlign from 'dom-align';
- AlignConfig
import { AlignConfig } from 'dom-align';import type { AlignConfig } from 'dom-align'; - AlignResult
import type { AlignResult } from 'dom-align';
Quickstart
import domAlign from 'dom-align';
// Create a source and target node for alignment demonstration.
// In a real application, these would be existing DOM elements.
const sourceNode = document.createElement('div');
sourceNode.id = 'sourceNode';
sourceNode.style.cssText = 'position:absolute; left:-9999px; top:-9999px; width:100px; height:50px; background-color:blue; color:white; padding:5px;';
sourceNode.textContent = 'I am the source!';
document.body.appendChild(sourceNode);
const targetNode = document.createElement('div');
targetNode.id = 'targetNode';
targetNode.style.cssText = 'position:relative; margin-top:150px; margin-left:200px; width:200px; height:100px; border:2px solid red; display:inline-block; padding:10px;';
targetNode.textContent = 'I am the target!';
document.body.appendChild(targetNode);
// Define the alignment configuration.
const alignConfig = {
points: ['tl', 'br'], // Align top-left of sourceNode with bottom-right of targetNode
offset: [5, 10], // Offset sourceNode by 5px in x, 10px in y after initial alignment
targetOffset: ['-10%', '-5%'], // Offset targetNode by -10% of its width, -5% of its height
overflow: { adjustX: true, adjustY: true }, // Auto-adjust position if sourceNode overflows viewport
};
// Perform the alignment. The function returns an AlignResult object.
const alignResult = domAlign(sourceNode, targetNode, alignConfig);
console.log('Alignment successful:', alignResult.align);
console.log('Adjustments made:', alignResult.overflow);
// To clean up or re-align, you might remove elements or call domAlign again with different configs.
// For demonstration, let's log the final position:
setTimeout(() => {
console.log(`Source node final position: left=${sourceNode.style.left}, top=${sourceNode.style.top}`);
}, 0);