I'm working on Nuxt.js project with Algolia search. I've got everything working apart from closing the search dropdown on clicking outside the box. I've looked at so many resources and nothing wants to work.
Here's where I've looked at:
Detect click outside element in nuxt
Detect click outside element on Vue 3
Would anybody be able to help, please?
Here's the current code I have:
plugins/click-outside.js
import Vue from 'vue';
Vue.directive('click-outside', {
bind: function (el, binding, vnode) {
el.clickOutsideEvent = function (event) {
console.log(el);
// here I check that click was outside the el and his childrens
if (!(el == event.target || el.contains(event.target))) {
// and if it did, call method provided in attribute value
vnode.context[binding.expression](event);
}
};
document.body.addEventListener('click', el.clickOutsideEvent)
},
unbind: function (el) {
document.body.removeEventListener('click', el.clickOutsideEvent)
},
});
index.vue
<template>
<div class="hello">
<div v-click-outside="closeDropdown">
Hello
</div>
</div>
</template>
<script>
methods: {
closeDropdown() {
console.log("Clicked outside closeDropdown!");
},
}
</script>