Skip to content
Advertisement

Detect click outside element

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:

Vue.directive('click-outside', {
  bind () {
      this.event = event => this.vm.$emit(this.expression, event)
      this.el.addEventListener('click', this.stopProp)
      document.body.addEventListener('click', this.event)
  },   
  unbind() {
    this.el.removeEventListener('click', this.stopProp)
    document.body.removeEventListener('click', this.event)
  },

  stopProp(event) { event.stopPropagation() }
})

Usage:

<div v-click-outside="nameOfCustomEventToCall">
  Some content
</div>

In the component:

events: {
  nameOfCustomEventToCall: function (event) {
    // do something - probably hide the dropdown menu / modal etc.
  }
}

Working Demo on JSFiddle with additional info about caveats:

https://jsfiddle.net/Linusborg/yzm8t8jq/

Advertisement