|
1 | 1 | # autoUpdate
|
2 | 2 |
|
3 |
| -This function adds listeners that automatically update the |
4 |
| -position of the floating element when required. |
| 3 | +This function adds listeners that automatically call an update |
| 4 | +function when necessary so that the floating element remains |
| 5 | +“anchored” to the reference element in a variety of scenarios |
| 6 | +without detaching. |
5 | 7 |
|
6 |
| -Only call this when the floating element is mounted to the DOM |
7 |
| -(or visible on the screen). |
| 8 | +```js |
| 9 | +autoUpdate(referenceEl, floatingEl, update, options); |
| 10 | +``` |
8 | 11 |
|
9 |
| -```js /autoUpdate/ |
10 |
| -import {computePosition, autoUpdate} from '@floating-ui/dom'; |
| 12 | +Only call this function when the floating element is mounted to |
| 13 | +the DOM (or visible on the screen). |
11 | 14 |
|
12 |
| -async function update() { |
13 |
| - const {x, y} = await computePosition(referenceEl, floatingEl); |
14 |
| -} |
| 15 | +```js |
| 16 | +import {computePosition, autoUpdate} from '@floating-ui/dom'; |
15 | 17 |
|
16 |
| -const cleanup = autoUpdate(referenceEl, floatingEl, update); |
| 18 | +const cleanup = autoUpdate(referenceEl, floatingEl, () => { |
| 19 | + computePosition(referenceEl, floatingEl).then(({x, y}) => { |
| 20 | + // ... |
| 21 | + }); |
| 22 | +}); |
17 | 23 | ```
|
18 | 24 |
|
19 | 25 | It returns a cleanup function that should be invoked when the
|
20 | 26 | floating element is no longer mounted on the DOM (or visible on
|
21 | 27 | the screen).
|
22 | 28 |
|
23 |
| -It does not call `update(){:js}` immediately, so for the first |
24 |
| -update, you should call the update function yourself. |
| 29 | +```js |
| 30 | +// Later, when the element is removed from the screen |
| 31 | +cleanup(); |
| 32 | +``` |
25 | 33 |
|
26 |
| -> By default, this requires a `ResizeObserver{:.class}`. To |
27 |
| -> support old browsers, either polyfill this constructor, or |
28 |
| -> disable the `elementResize{:.objectKey}` option and update |
29 |
| -> manually. |
| 34 | +> The update function is called immediately by default and |
| 35 | +> requires a `ResizeObserver{:.class}`. |
30 | 36 |
|
31 | 37 | ## Options
|
32 | 38 |
|
@@ -75,6 +81,12 @@ default: `true{:js}`
|
75 | 81 | Whether to update the position when either the reference or
|
76 | 82 | floating elements resized. This uses a `ResizeObserver{:.class}`.
|
77 | 83 |
|
| 84 | +To support old browsers, polyfill the constructor, or disable |
| 85 | +this option and update manually when the elements resize. |
| 86 | + |
| 87 | +> Disabling this means `autoUpdate(){:js}` will no longer call |
| 88 | +> your update function immediately. |
| 89 | +
|
78 | 90 | ```js
|
79 | 91 | const cleanup = autoUpdate(referenceEl, floatingEl, update, {
|
80 | 92 | elementResize: false,
|
|
0 commit comments