Skip to content

useElementBounding ​

Category
Export Size
1.15 kB
Last Changed
2 months ago

Reactive bounding box of an HTML element

Demo ​

Resize the box to see changes

Usage ​

vue
<script>
import { useElementBounding } from '@vueuse/core'
import { ref } from 'vue'

export default {
  setup() {
    const el = ref(null)
    const { x, y, top, right, bottom, left, width, height }
        = useElementBounding(el)

    return {
      el,
      /* ... */
    }
  },
}
</script>

<template>
  <div ref="el" />
</template>

Component Usage ​

This function also provides a renderless component version via the @vueuse/components package. Learn more about the usage.

vue
<template>
  <UseElementBounding v-slot="{ width, height }">
    Width: {{ width }} Height: {{ height }}
  </UseElementBounding>
</template>

Type Declarations ​

Show Type Declarations
typescript
export interface UseElementBoundingOptions {
  /**
   * Reset values to 0 on component unmounted
   *
   * @default true
   */
  reset?: boolean
  /**
   * Listen to window resize event
   *
   * @default true
   */
  windowResize?: boolean
  /**
   * Listen to window scroll event
   *
   * @default true
   */
  windowScroll?: boolean
  /**
   * Immediately call update on component mounted
   *
   * @default true
   */
  immediate?: boolean
  /**
   * Timing to recalculate the bounding box
   *
   * Setting to `next-frame` can be useful when using this together with something like {@link useBreakpoints}
   * and therefore the layout (which influences the bounding box of the observed element) is not updated on the current tick.
   *
   * @default 'sync'
   */
  updateTiming?: "sync" | "next-frame"
}
/**
 * Reactive bounding box of an HTML element.
 *
 * @see https://vueuse.org/useElementBounding
 * @param target
 */
export declare function useElementBounding(
  target: MaybeComputedElementRef,
  options?: UseElementBoundingOptions,
): {
  height: Ref<number, number>
  bottom: Ref<number, number>
  left: Ref<number, number>
  right: Ref<number, number>
  top: Ref<number, number>
  width: Ref<number, number>
  x: Ref<number, number>
  y: Ref<number, number>
  update: () => void
}
export type UseElementBoundingReturn = ReturnType<typeof useElementBounding>

Source ​

Source • Demo • Docs

Contributors ​

Anthony Fu
Jelf
wheat
Anthony Fu
Jonas Schade
huiliangShen
vaakian X
Ducz01
hsyq
Hebilicious
webfansplz
Ciro Lo Sapio
Shinigami
Alex Kozack

Changelog ​

v11.0.0-beta.2 on 7/17/2024
0fa17 - feat: add updateTiming option (#3869)
v10.7.1 on 12/27/2023
70dbd - fix: trigger by css or style (#3664)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v9.10.0 on 1/3/2023
268a6 - fix: update on scroll (#2596)

Released under the MIT License.