[Vuejs]-How to check clicks of the user in order to toggle popup? [VueJS]

0đź‘Ť

I think all you need to do is adding a custom directive to handle the clicks outside that element (i.e., the popup).

Vue.directive('click-outside', {
  bind: function (el, binding, vnode) {
    el.event = function (event) {
      // here I check that click was outside the el and his childrens
      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.event)
  },
  unbind: function (el) {
    document.body.removeEventListener('click', el.event)
  },
});

Here’s a working demo

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

0đź‘Ť

Try this… Sadly, it uses the powerfull jQuery library.

let element = $(event.target),
allCard = $(document).find('.popup'),
pointer_popup = element.closest('.popup').length,
pointer_card = element.closest('.card-item').length;

if (pointer_popup == 0 && pointer_card == 0) {
  allCard.hide();
}

You want to check if there is a “closest” element… Check the length of the resulting jQuery lookup.

Leave a comment