Skip to content

useFocusWithin

Category
Export Size
1.37 kB
Last Changed
6 months ago

Reactive utility to track if an element or one of its decendants has focus. It is meant to match the behavior of the :focus-within CSS pseudo-class. A common use case would be on a form element to see if any of its inputs currently have focus.

Demo

Focus in form: false

Basic Usage

vue
<script setup lang="ts">
import { 
useFocusWithin
} from '@vueuse/core'
import {
ref
,
watch
} from 'vue'
const
target
=
ref
()
const {
focused
} =
useFocusWithin
(
target
)
watch
(
focused
, (
focused
) => {
if (
focused
)
console
.
log
('Target contains the focused element')
else
console
.
log
('Target does NOT contain the focused element')
}) </script> <template> <
form
ref
="
target
">
<
input
type
="text"
placeholder
="First Name">
<
input
type
="text"
placeholder
="Last Name">
<
input
type
="text"
placeholder
="Email">
<
input
type
="text"
placeholder
="Password">
</
form
>
</template>

Type Declarations

ts
export interface UseFocusWithinReturn {
  /**
   * True if the element or any of its descendants are focused
   */
  
focused
:
ComputedRef
<boolean>
} /** * Track if focus is contained within the target element * * @see https://vueuse.org/useFocusWithin * @param target The target element to track * @param options Focus within options */ export declare function
useFocusWithin
(
target
:
MaybeElementRef
,
options
?:
ConfigurableWindow
,
): UseFocusWithinReturn

Source

SourceDemoDocs

Contributors

Anthony Fu
Anthony Fu
Ben Lau
SerKo
IlyaL
Fernando Fernández
sun0day
Mikhailov Nikita
Boris Moiseev
Jelf
William T. Kirby

Changelog

v12.4.0 on
dd316 - feat: use passive event handlers everywhere is possible (#4477)
v12.3.0 on
3ca0d - fix: correctly track the state when switching the focus of elements in the same container (#4394)
v12.0.0-beta.1 on
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)
v11.1.0 on
c5407 - fix: make useFocusWhithin match the behavior of the :focus-within (#4134)
v10.0.0-beta.3 on
e75a5 - feat: update deps

Released under the MIT License.

Build faster with AI
New Masterclass to help you leverage AI in your Vue workflow
Get Early Access