0

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

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>
Rafal Adam Krohne
  • 437
  • 1
  • 3
  • 15
  • Can you please provide the code you are trying to apply this to? – aside Mar 30 '21 at 10:13
  • I've edited the content above, thank you. – Rafal Adam Krohne Mar 30 '21 at 10:31
  • The code containing the search dropdown would be quite helpful as well. Ideally you would provide a codesandbox sample, it is difficult to help you find a solution otherwise. – aside Mar 30 '21 at 10:49
  • I've done something 99% similar what I have on my project: https://codesandbox.io/s/thirsty-cerf-vpply I've managed to get the click outside the box correctly. (Although my own project console.log everything twice for some reason :/ ) Getting back to SandBox....I'd like to clear the input and hide the results on clicking outside the box but I'm not sure what I'm doing wrong :( – Rafal Adam Krohne Mar 30 '21 at 14:36

0 Answers0