Sometimes, we want to detect clicks outside an element with Vue.js.
In this article, we’ll look at how to detect clicks outside an element with Vue.js.
Detect Clicks Outside an Element with Vue.js
We can detect clicks outside an element with Vue.js by creating our own directive.
For instance, we can write:
<template>
<div id="app" style="width: 500px; height: 500px">
<div v-click-outside="onClickOutside">hello world</div>
</div>
</template>
<script>
import Vue from "vue";
Vue.directive("click-outside", {
bind(el, binding, vnode) {
el.clickOutsideEvent = (event) => {
if (!(el === event.target || el.contains(event.target))) {
vnode.context[binding.expression](event);
}
};
document.body.addEventListener("click", el.clickOutsideEvent);
},
unbind(el) {
document.body.removeEventListener("click", el.clickOutsideEvent);
},
});
export default {
name: "App",
methods: {
onClickOutside() {
console.log("clicked outside");
},
},
};
</script>
We call Vue.directive
with the directive name and an object that has the bind
and unbind
methods to add the el.clickOutsideEvent
method in the bind
method.
In clickOutsideEvent
, we check if el
isn’t event.target
and that it doesn’t contain event.target
.
If both are true
, then we add vnode.context[binding.expression](event);
to run the method that we set as the value of the v-click-outside
directive.
Then we call document.body.addEventListener
to add a click event listener to run clickOutsideEvent
.
In the unbind
method, we remove the event listener with removeEventListener
when we unbind the directive.
Then in the template, we add v-click-outside
and set the value of it to onClickOutside
to run the method when we click outside.
When we click outside, we should see 'clicked outside'
logged.
Conclusion
We can detect clicks outside an element with Vue.js by creating our own directive.