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;
};

nextFrame

Schedules a callback to be executed on the next animation frame.

/**
 * Schedules a callback to be executed on the next animation frame.
 *
 * @example
 * const cancel = nextFrame(() => {
 *   // Code to run after the next paint
 * });
 * // To cancel the scheduled callback:
 * cancel();
 */
export const nextFrame = (cb: (...args: unknown[]) => void, numFrames = 1) => {
  let id: number;
 
  const frame = (remaining: number) => {
    if (remaining > 1) {
      id = requestAnimationFrame(() => frame(remaining - 1));
    } else {
      id = requestAnimationFrame(() => cb());
    }
  };
 
  frame(numFrames);
 
  return () => cancelAnimationFrame(id);
};

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);
};