Tracking global click events in Vue.js can provide valuable insights into user interactions on your

While working with JavaScript, I was able to create this code for a popover. By clicking on the navbar-link element, the popover will appear or disappear. However, it would be great if I could close the popover by clicking anywhere on the screen (when the popover is open).

Does anyone have any ideas on how to achieve this?

<template>
  <div>
    <span class="navbar-link" v-on:click="toggle()">
      <i class="ion-android-notifications-none"></i>
    </span>
    <div class="popover" v-bind:class="{ 'open': opened }">
      Hello, world!
    </div>
  </div>
</template>
<script>
  export default{
    data(){
      return {
        opened: false
      }
    },
    methods: {
      toggle: function () {
        this.opened = !this.opened;
      }
    }
  }
</script>

Thank you in advance :)

Answer №1

Utilizing global JavaScript functions and binding events to the document element is still possible:

export default {
    data () {
        return {
            isOpen: false
        }
    },
    methods: {
        toggle () {
            if (this.isOpen) {
                return this.hide()
            }
            return this.show()
        },
        show () {
            this.isOpen = true;
            setTimeout(() => document.addEventListener('click', this.hide), 0);
        },
        hide () {
            this.isOpen = false;
            document.removeEventListener('click', this.hide);
        }
    }
}

This approach enables closing the popover by clicking on it as well. However, it requires preventing click events from propagating on the popover container:

<div class="popover" v-bind:class="{ 'open': isOpen }" @click.stop>
    Hello, world!
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unique column arrangement specifically designed for the initial row within the loop

My webpage features a layout that showcases 4 images on each row. However, I am looking to create a special first row with a unique column configuration compared to the rest of the rows. Here is an example of what I have in mind: https://i.sstatic.net/Rs ...

Update data dynamically on a div element using AngularJS controller and ng-repeat

I am currently navigating my way through Angular JS and expanding my knowledge on it. I have a div set up to load data from a JSON file upon startup using a controller with the following code, but now I am looking to refresh it whenever the JSON object cha ...

What steps are needed to configure ESLint to exclusively analyze .ts files?

I need ESLint to exclusively focus on processing .ts files and not .js files. In order to achieve that, I made a .eslintignore file and included the following lines: *.js **/*.js Nevertheless, it appears that ESLint is disregarding this file. Is there so ...

Troubleshooting the error "The 'listener' argument must be a function" in Node.js HTTP applications

I'm facing an issue resolving this error in my code. It works perfectly fine on my local environment, but once it reaches the 'http.get' call, it keeps throwing the error: "listener argument must be a function." Both Nodejs versions are iden ...

How to reposition the Bootstrap navbar Logo from the left to the center

I am looking to change the ordering of Bootstrap 4 Navbar. Currently, the logo is on the left side, but I want it in the center with menus on both sides. Can someone help me with changing this order? Check out the current Navbar layout below: <nav c ...

Changing the height of one Div based on another Div's height

I currently have a display of four divs positioned side by side. I am seeking a solution to ensure that the height of each div remains consistent, and should adjust accordingly if one of them increases in size due to added text content. For reference, ple ...

Error: The function 'fetch' is not recognized in Selenium Console

Having some trouble with Selenium and Chrome Developer Tools. I want to open Selenium, go to a URL, and then use driver.execute_script to make a fetch request via Console in Chrome Developer Tools within the Selenium window. However, when I try to run thi ...

Ways to extract subarray elements that meet a certain condition and break out of the loop

const winningTemplate = { firstRow: [0, 1, 2, 3, 4], secondRow: [5, 6, 7, 8, 9], thirdRow: [10, 11, 13, 14], fourthRow: [15, 16, 17, 18, 19], lastRow: [20, 21, 22, 23, 24], firstDiagonal: [0, 6, 18, 24], firstColumn: [0, 5, 10, ...

Loop Through Mongoose to Retrieve Multiple Objects

I am currently facing an issue while trying to retrieve multiple objects from MongoDB using mongoose. In my database, I have two primary collections known as user and order. The user collection consists of an array called 'order history', which ...

When properties are passed and then mapped, they become undefined

While I experience no errors when directly mapping the array, passing the same array through props results in an error stating "Cannot read property 'map' of undefined." Brands Array const brands = [ { key: 1, Name: "Nike", }, { ...

What could be causing my state not to change in Nextjs even though I followed the quick start guide for Easy Peasy?

I recently encountered an issue while trying to implement easy peasy for global state management in my nextjs app. The problem I faced was that the state would only update when I changed pages, which seemed odd. To better understand what was going on, I de ...

Executing a NestJs cron job at precise intervals three times each day: a guide

I am developing a notifications trigger method that needs to run three times per day at specific times. Although I have reviewed the documentation, I am struggling to understand the regex code and how to customize it according to my requirements! Current ...

Tips for transferring the clicked value to the next page

Recently, I started working with Ionic and developed an application using it. Now, I am facing a challenge where I need to pass the value from the first page to the second page. To illustrate this more clearly, I have attached two photos. Here is the imag ...

Problems with Bootstrap affix scrolling in Internet Explorer and Firefox

I'm encountering an issue with the sidebar on my website. I've implemented Bootstrap affix to keep it fixed until the end of the page, where it should move up along with the rest of the content at a specific point... Everything seems to be worki ...

Enhancing Your Vue Experience: A Guide to Highlighting and Selecting HTML Elements on Mouse Hover

Incorporating a navigation header using Vue, I utilize v-html to display it seamlessly. Check out the demo - here <section class="text-gray-700 font-heading font-medium relative bg-gray-50 bg-opacity-50"> <nav class="flex justify ...

Using Angular as a template engine: A simple guide

My goal is to utilize Angular as a template engine and then pass the resulting HTML code to another library. In my template file named template.html: <div><h1><span data-ng-show="details.rs">{{details.rs}}</span></h1></di ...

Having trouble showing images from block content using PortableText?

It's been quite a while now that I've been stuck on this issue. Despite being in a learning phase, I find myself unable to progress due to this specific problem. While links and text elements are functioning properly, I have encountered difficul ...

Strategies for binding props to input values in Vuejs

Currently, I have a parent component called Cart where I have defined the quantity. My goal is to pass this quantity to the child component Counter. Below is how I am passing it within my parent component: <Counter quantity="item.quantity"/> ...

Transferring a zipped file between a Node.js server and a Node.js client

I am facing an issue with sending a zip file from a node.js server to a node.js client. The problem is that when I try to save the zip file, it becomes corrupted and cannot be opened. To create and send the zip file to the client, I am using the adm-zip l ...

Make sure to validate onsubmit and submit the form using ajax - it's crucial

Seeking assistance for validating a form and sending it with AJAX. Validation without the use of ''onsubmit="return validateForm(this);"'' is not functioning properly. However, when the form is correct, it still sends the form (page r ...