DOM
A collection of utility functions for common DOM operations.
getCssValueLength
Extracts the numeric pixel value from a CSS value.
export const getCssValueLength = (value: string): number => {
const temp = document.createElement("div");
temp.setAttribute("inert", "");
temp.style.cssText = `position:absolute;visibility:hidden;width:${value};`;
document.body.appendChild(temp);
const pixels = temp.offsetWidth;
document.body.removeChild(temp);
return pixels;
};
scrollIntoViewIfNeeded
Scrolls an element into view if it is not already in view, and its parent element is scrollable.
export const scrollIntoViewIfNeeded = (
root: HTMLElement,
target: HTMLElement,
options: Omit<ScrollToOptions, "left" | "top"> = {}
) => {
const hasVerticalScroll = root.scrollHeight > root.clientHeight;
const hasHorizontalScroll = root.scrollWidth > root.clientWidth;
const scrollOptions: ScrollToOptions = { ...options };
if (hasVerticalScroll) {
scrollOptions.top = target.offsetTop - root.offsetTop;
}
if (hasHorizontalScroll) {
scrollOptions.left = target.offsetLeft - root.offsetLeft;
}
root.scrollTo(scrollOptions);
};