Skip to content

Instantly share code, notes, and snippets.

@JodiWarren
Forked from cecigarcia/measure-dom-node.js
Last active July 4, 2021 22:26
Show Gist options
  • Save JodiWarren/19a24af76bd62eee06a282fb329771ba to your computer and use it in GitHub Desktop.
Save JodiWarren/19a24af76bd62eee06a282fb329771ba to your computer and use it in GitHub Desktop.
const containerStyle = {
display: "inline-block",
position: "absolute",
visibility: "hidden",
zIndex: -1,
};
interface IEnhanceMeasurableNodeCallback {
(e: Node): Node;
}
export const measureDomNode = (
node: HTMLElement,
enhanceMeasurableNode: IEnhanceMeasurableNodeCallback = (e) => e
) => {
const container = document.createElement("div");
Object.entries(containerStyle).forEach(([prop, value]) => {
// @ts-ignore
container.style[prop] = value;
});
const clonedNode = node.cloneNode(true);
const content = enhanceMeasurableNode(clonedNode);
container.appendChild(content);
if (node.parentNode) {
node.parentNode.appendChild(container);
} else {
document.body.appendChild(container);
}
const height = container.clientHeight;
const width = container.clientWidth;
container.parentNode?.removeChild(container);
return { height, width };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment