Vue 2.x directive to react on events outside of an element
vue-outside-events
Vue 2.x directive to react on events outside of an element without stopping the event's propagation.
Works well for handling clicks outside of menus and popups. Can handle any DOM event or CustomEvent. Also able to capture jQuery events.
Install
npm install --save vue-outside-events
Demos
Check out the highly contrived demos here: https://nchutchind.github.io/vue-outside-events/docs/index.html
Use
Modular
import Vue from 'vue'
import vOutsideEvents from 'vue-outside-events'
Vue.use(vOutsideEvents)
<script>
export default {
methods: {
onClickOutside (e, el) {
console.log('onClickOutside');
console.log('click heard outside element: ', el);
console.log('element clicked: '. e.target);
console.log('event: ', e);
},
onMouseOutside (e, el) {
console.log('onMouseOutside');
console.log('mouse moved outside element: ', el);
console.log('element mouse moved over: '. e.target);
console.log('event: ', e);
}
}
};
</script>
<template>
<div v-click-outside="onClickOutside"></div>
<div v-mousemove-outside="onMouseOutside"></div>
</template>
Scripts
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js" type="text/javascript"></script>
<script src="js/v-outside-events.min.js" type="text/javascript"></script>
<div id="app">
<div v-click-outside="onClickOutside"></div>
<div v-mousemove-outside="onMouseOutside"></div>
</div>
<script>
new Vue({
el: '#app',
methods: {
onClickOutside (e, el) {
console.log('onClickOutside');
console.log('click heard outside element: ', el);
console.log('element clicked: '. e.target);
console.log('event: ', e);
},
onMouseOutside (e, el) {
console.log('onMouseOutside');
console.log('mouse moved outside element: ', el);
console.log('element mouse moved over: '. e.target);
console.log('event: ', e);
}
}
});
</script>
Modifiers
Add the jquery
modifier to allow the directive to handle jQuery triggering of custom events. jQuery must be present in the window for this to work.
<div id="myDiv1" v-event-outside="{ name: 'onFoo', handler: onFooOutside }"></div>
<div id="myDiv2" v-event-outside.jquery="{ name: 'onFoo', handler: onFooOutside }"></div>
<script>
$(document).trigger("onFoo"); // onFooOutside will be called for #myDiv2, but not #myDiv1
var event = document.createEvent('Event');
event.initEvent('onFoo', true, true);
document.dispatchEvent(event); // onFooOutside will be called for #myDiv1 and #myDiv2
</script>