How can I detect a click outside my element? I’m using Vue.js so it’s gonna be outside my templates element. I know how to do it in Vanilla JS, but I’m not sure if there’s a more proper way to do it, when I’m using Vue.js?
This is the solution for Vanilla JS: Javascript Detect Click event outside of div
I guess I can use a better way to access the element?
Advertisement
Answer
Keep in attention that this solution only works with Vue 1.
Can be solved nicely by setting up a custom directive once:
JavaScript
x
14
14
1
Vue.directive('click-outside', {
2
bind () {
3
this.event = event => this.vm.$emit(this.expression, event)
4
this.el.addEventListener('click', this.stopProp)
5
document.body.addEventListener('click', this.event)
6
},
7
unbind() {
8
this.el.removeEventListener('click', this.stopProp)
9
document.body.removeEventListener('click', this.event)
10
},
11
12
stopProp(event) { event.stopPropagation() }
13
})
14
Usage:
JavaScript
1
4
1
<div v-click-outside="nameOfCustomEventToCall">
2
Some content
3
</div>
4
In the component:
JavaScript
1
6
1
events: {
2
nameOfCustomEventToCall: function (event) {
3
// do something - probably hide the dropdown menu / modal etc.
4
}
5
}
6
Working Demo on JSFiddle with additional info about caveats: