autoUpdate
This function adds listeners that automatically call an update function when necessary so that the floating element remains “anchored” to the reference element in a variety of scenarios without detaching.
autoUpdate(referenceEl, floatingEl, update, options);
Only call this function when the floating element is mounted to the DOM (or visible on the screen).
import {computePosition, autoUpdate} from '@floating-ui/dom';
const cleanup = autoUpdate(referenceEl, floatingEl, () => {
computePosition(referenceEl, floatingEl).then(({x, y}) => {
// ...
});
});
It returns a cleanup function that should be invoked when the floating element is no longer mounted on the DOM (or visible on the screen).
// Later, when the element is removed from the screen
cleanup();
The update function is called immediately by default and requires a
ResizeObserver
.
Options
These are the options you can pass as a fourth argument to
autoUpdate()
.
interface Options {
ancestorScroll?: boolean;
ancestorResize?: boolean;
elementResize?: boolean;
animationFrame?: boolean;
}
ancestorScroll
default: true
Whether to update the position when an overflow ancestor is scrolled.
const cleanup = autoUpdate(referenceEl, floatingEl, update, {
ancestorScroll: false,
});
ancestorResize
default: true
Whether to update the position when an overflow ancestor is
resized. This uses the resize
event.
const cleanup = autoUpdate(referenceEl, floatingEl, update, {
ancestorResize: false,
});
elementResize
default: true
Whether to update the position when either the reference or
floating elements resized. This uses a ResizeObserver
.
To support old browsers, polyfill the constructor, or disable this option and update manually when the elements resize.
Disabling this means
autoUpdate()
will no longer call your update function immediately.
const cleanup = autoUpdate(referenceEl, floatingEl, update, {
elementResize: false,
});
animationFrame
default: false
Whether to update the position of the floating element on every animation frame if required. This is optimized for performance but can still be costly.
Setting this to true
disables the scroll, resize, and
reference ResizeObserver
listeners as they become
unnecessary. Only the floating element's
ResizeObserver
remains active, if
elementResize
is true
.
const cleanup = autoUpdate(referenceEl, floatingEl, update, {
animationFrame: true,
});
This option should be used sparingly but can also automatically handle layout changes where the reference element moves on the screen, which none of the other options can handle.