Skip to content

useMouseInElement

Category
Export Size
1.12 kB
Last Changed
5 months ago

Reactive mouse position related to an element

Demo

Hover me
x: 0
y: 0
sourceType: null
elementX: 0
elementY: 0
elementPositionX: 0
elementPositionY: 0
elementHeight: 0
elementWidth: 0
isOutside: true

Usage

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

const target = ref(null)

const { x, y, isOutside } = useMouseInElement(target)
</script>

<template>
  <div ref="target">
    <h1>Hello world</h1>
  </div>
</template>

Component Usage

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

vue
<template>
  <UseMouseInElement v-slot="{ elementX, elementY, isOutside }">
    x: {{ elementX }}
    y: {{ elementY }}
    Is Outside: {{ isOutside }}
  </UseMouseInElement>
</template>

Type Declarations

typescript
export interface MouseInElementOptions extends UseMouseOptions {
  handleOutside?: boolean
}
/**
 * Reactive mouse position related to an element.
 *
 * @see https://vueuse.org/useMouseInElement
 * @param target
 * @param options
 */
export declare function useMouseInElement(
  target?: MaybeElementRef,
  options?: MouseInElementOptions,
): {
  x: Ref<number>
  y: Ref<number>
  sourceType: Ref<UseMouseSourceType>
  elementX: Ref<number>
  elementY: Ref<number>
  elementPositionX: Ref<number>
  elementPositionY: Ref<number>
  elementHeight: Ref<number>
  elementWidth: Ref<number>
  isOutside: Ref<boolean>
  stop: () => void
}
export type UseMouseInElementReturn = ReturnType<typeof useMouseInElement>

Source

SourceDemoDocs

Contributors

Anthony Fu
wheat
Aymoc
Mikhailov Nikita
vaakian X
Jelf
Ivan Agafonov
Shinigami
Alex Kozack
ctholho
Nurettin Kaya
Antério Vieira

Changelog

v10.7.0 on 12/5/2023
fccf2 - feat: upgrade deps (#3614)
v10.6.0 on 11/9/2023
7c88d - fix: optimize outside computation (#3380)
v9.12.0 on 1/29/2023
54f4e - fix: check if mouse out of window (#2458)
v9.11.0 on 1/17/2023
d5321 - fix(components): mark defineComponent as pure (#2623)
v8.9.3 on 7/14/2022
4d2c8 - fix(useMouse)!: rename type MouseOptions to UseMouseOptions (#1877)

Released under the MIT License.