packages/core/onClickOutside/index.md
Listen for clicks outside of an element. Useful for modals or dropdowns.
<script setup lang="ts">
import { onClickOutside } from '@vueuse/core'
import { useTemplateRef } from 'vue'
const target = useTemplateRef('target')
onClickOutside(target, event => console.log(event))
</script>
<template>
<div ref="target">
Hello world
</div>
<div>Outside element</div>
</template>
By default, onClickOutside returns a stop function to remove the event listeners.
const stop = onClickOutside(target, handler)
// Later, stop listening
stop()
If you need more control over triggering the handler, you can use the controls option. This returns an object with stop, cancel, and trigger functions.
const { stop, cancel, trigger } = onClickOutside(
modalRef,
(event) => {
modal.value = false
},
{ controls: true },
)
// cancel prevents the next click from triggering the handler
cancel()
// trigger manually fires the handler
trigger(event)
// stop removes all event listeners
stop()
Use the ignore option to prevent certain elements from triggering the handler. Provide elements as an array of Refs or CSS selectors.
const ignoreElRef = useTemplateRef('ignoreEl')
onClickOutside(
target,
event => console.log(event),
{ ignore: [ignoreElRef, '.ignore-class', '#ignore-id'] },
)
By default, the event listener uses the capture phase (capture: true). Set capture: false to use the bubbling phase instead.
onClickOutside(target, handler, { capture: false })
Clicks inside an iframe are not detected by default. Enable detectIframe to also trigger the handler when focus moves to an iframe.
onClickOutside(target, handler, { detectIframe: true })
<template>
<OnClickOutside :options="{ ignore: [/* ... */] }" @trigger="count++">
<div>
Click Outside of Me
</div>
</OnClickOutside>
</template>
<script setup lang="ts">
import { vOnClickOutside } from '@vueuse/components'
import { shallowRef } from 'vue'
const modal = shallowRef(false)
function closeModal() {
modal.value = false
}
</script>
<template>
<button @click="modal = true">
Open Modal
</button>
<div v-if="modal" v-on-click-outside="closeModal">
Hello World
</div>
</template>
You can also set the handler as an array to set the configuration items of the instruction.
<script setup lang="ts">
import { vOnClickOutside } from '@vueuse/components'
import { shallowRef, useTemplateRef } from 'vue'
const modal = shallowRef(false)
const ignoreElRef = useTemplateRef('ignoreEl')
const onClickOutsideHandler = [
(ev) => {
console.log(ev)
modal.value = false
},
{ ignore: [ignoreElRef] },
]
</script>
<template>
<button @click="modal = true">
Open Modal
</button>
<div ref="ignoreElRef">
click outside ignore element
</div>
<div v-if="modal" v-on-click-outside="onClickOutsideHandler">
Hello World
</div>
</template>