Detect click outside element

user6102188 picture user6102188 · Mar 23, 2016 · Viewed 118.5k times · Source

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?

Answer

MadisonTrash picture MadisonTrash · Feb 22, 2017

There is the solution I used, which is based on Linus Borg answer and works fine with vue.js 2.0.

Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    el.clickOutsideEvent = function (event) {
      // here I check that click was outside the el and his children
      if (!(el == event.target || el.contains(event.target))) {
        // and if it did, call method provided in attribute value
        vnode.context[binding.expression](event);
      }
    };
    document.body.addEventListener('click', el.clickOutsideEvent)
  },
  unbind: function (el) {
    document.body.removeEventListener('click', el.clickOutsideEvent)
  },
});

You bind to it using v-click-outside:

<div v-click-outside="doStuff">

Here's a small demo

You can find some more info about custom directives and what el, binding, vnode means in https://vuejs.org/v2/guide/custom-directive.html#Directive-Hook-Arguments