Created
June 14, 2022 08:17
-
-
Save KarmaBlackshaw/2373fac25cef300c7dc1ce1e7f2e14e8 to your computer and use it in GitHub Desktop.
Vue 2 Directive: Click Outside
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
directives: { | |
clickOutside: { | |
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 | |
if (typeof binding.value === 'function') { | |
binding.value() | |
} | |
} | |
} | |
document.body.addEventListener('click', el.clickOutsideEvent) | |
}, | |
unbind: function (el) { | |
document.body.removeEventListener('click', el.clickOutsideEvent) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment