Function positionFn

Returns a function which yields element position in target coordinate space with optional scaling. Live position is calculated when the function is invoked. Use positionRelative to simply get relative position of element in given coordinate space.

const f = positionFn('#blah');
f(); // Yields: {x,y}
// Or:
positionFn('#blah')(); // Immediately invoke
const f = positionFn(evt.target, { relative: true });
f(); // Yields: {x,y}
const f = positionFn('#blah', { target: 'screen', relative: true });
f(); // Yields: {x,y}

By default, top-left corner (north west) is used. Other cardinal points or 'center' can be specified:

// Relative position by center
positionFn('#blah', { relative: true, anchor: 'center' });

// ...by bottom-right corner
positionFn('#blah', { relative: true, anchor: 'se' });

This function is useful if you have a stable DOM element and conversion target. If the DOM element is changing continually, consider using viewportToSpace to convert from viewport coordinates to target coordinates:

// Eg.1 Absolute coords in screen space
const vpToScreen = viewportToSpace('screen');
vpToScreen(el.getBoundingClientRect());

// Eg.2 Relative coords in viewport space
const vpRelative = pointScaler(); // Re-usable scaler. Default uses viewport
vpRelative(el.getBoundingClientRect()); // Yields: { x,y }

// Eg.3 Relative coords in screen space
const vpToScreen = viewportToSpace('screen'); // Map viewport->screen
const screenRelative = pointScaler('screen'); // Scale screen units

// Combine into a resuable function that takes an element
const mapAndScale = (el) => screenRelative(vpToScreen(el.getBoundingClientRect()));

// Call
mapAndScale(document.getElementById('blah')); // Yields: { x,y }
  • Parameters

    • domQueryOrEl: Readonly<string | HTMLElement>
    • options: ElPositionOpts = {}

    Returns (() => Point)