Skip to content

Instantly share code, notes, and snippets.

@jbruni
Created December 14, 2016 02:25
Show Gist options
  • Save jbruni/6a879ae2313c2713c71881617089ff23 to your computer and use it in GitHub Desktop.
Save jbruni/6a879ae2313c2713c71881617089ff23 to your computer and use it in GitHub Desktop.
v-click-outside directive
/**
* v-click-outside directive
*/
import Vue from 'vue'
import $ from 'jquery'
let elements = []
Vue.directive('click-outside', {
bind: (el, binding) => {
bindClickOutside(el, binding.value)
},
unbind: (el, binding) => {
unbindClickOutside(el)
}
})
function bindClickOutside(el, handler) {
elements.push({ el, handler })
}
function unbindClickOutside(el) {
$.each(elements, (index, item) => {
if (item.el === el) {
elements.splice(index, 1)
return false
}
})
}
$(document).on('click', (e) => {
elements.forEach(item => {
let $el = $(item.el)
if (!$el.is(':animated')
&& $el.is(':visible')
&& $(e.target).closest(item.el).length === 0
) {
item.handler(e)
}
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment