Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// This variable will hold the reference to the document's click handler
let handleOutsideClick
// Difining clickoutside globally for the application
// so it will be used across all the components
Vue.directive('clickoutside', {
// bind the logic to the html element
bind (el, binding, vnode) {
// Here's the click/touchstart handler
// (it is registered below)
handleOutsideClick = (e) => {
e.stopPropagation();
console.log('test')
// get the bind values from the element on which directive is used
const { exclude } = binding.value;
// check whether the clicked element is same as passed referenece
// if clicked element same as passed refernece then we checked
// whether popup is visible or hide
if(vnode.context.$refs[exclude[0]].contains(e.target)){
if(!el.classList.contains('show')){
el.classList.add('show')
}else{
el.classList.remove('show')
}
}
// if user click outside except passed referance element
// then we just hide the popup
else{
// if( !el.contains(e.target))
el.classList.remove('show')
}
}
// Register click/touchstart event listeners on the whole page
document.addEventListener('click', handleOutsideClick)
document.addEventListener('touchstart', handleOutsideClick)
},
unbind () {
// If the element that has v-clickoutside is removed, then
// unbind click/touchstart listeners from the whole page
document.removeEventListener('click', handleOutsideClick)
document.removeEventListener('touchstart', handleOutsideClick)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.