Blog>
Snippets

Click Outside Directive

Implement a directive that detects clicks outside of the bound element, often used for closing modals or dropdown menus.
Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    el.clickOutsideEvent = function (event) {
      if (!(el == event.target || el.contains(event.target))) {
        vnode.context[binding.expression](event);
      }
    };
    document.body.addEventListener('click', el.clickOutsideEvent)
  },
  unbind: function (el) {
    document.body.removeEventListener('click', el.clickOutsideEvent)
  },
});
Creates a Vue directive called 'click-outside' that listens for clicks on the body of the document. If a click occurs outside the element to which the directive is bound, the handler specified in the expression is called. It also cleans up the event listener when the element is unbound.