Skip to content

Instantly share code, notes, and snippets.

@ravipatel2293
Created April 6, 2019 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ravipatel2293/12cf721a014327c37b5b9a114e2b2bf8 to your computer and use it in GitHub Desktop.
Save ravipatel2293/12cf721a014327c37b5b9a114e2b2bf8 to your computer and use it in GitHub Desktop.
// 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