DOM utils
All helpers specific to the DOM available from package root.
import { findAncestor, getPositionedParentOffset, isScrollable } from '@krutoo/utils';
isScrollable
Checks that element is scrollable.
import { isScrollable } from '@krutoo/utils';
const element = document.querySelector('#something');
isScrollable(element); // true or false
findAncestor
Finds closest ancestor element that matches condition.
import { findAncestor } from '@krutoo/utils';
const element = document.querySelector('#something');
// element or null returns
const closestTarget = findAncestor(element, parent => parent.classList.contains('target'));
getPositionedParentOffset
Returns position of top left corner of the parent positioned element relative to viewport origin. Useful when you need to visually move element to position relative to viewport.
- It works for elements with any ancestors in any subtrees of your DOM
- It works for
absoluteandfixedpositioning
For example when you need to move element to mouse you can do this:
import { getPositionedParentOffset } from '@krutoo/utils';
const element = document.querySelector('#something');
window.addEventListener('mousemove', event => {
const offset = getPositionedParentOffset(element);
element.style.top = `${event.clientY - offset.y}px`;
element.style.left = `${event.clientX - offset.x}px`;
});