Concealing a Vuejs dropdown when clicking outside of the component

I am currently working on a Vuejs project where I am creating a menu component. This menu consists of 2 dropdowns, and I have already implemented some methods and used Vue directives to ensure that when one dropdown is clicked, the other hides and vice versa. However, I am also interested in figuring out a way to hide the dropdowns by clicking outside of them.

I have tried using 2 Vue libraries for this purpose, but unfortunately, they did not work as expected. Ideally, I would like to accomplish this manually within the project without relying on external resources.

Here is the HTML code for the menu:

<!-- menu -->
<div>
  <ul>
    <li><span>Home</span></li>
    <li v-on:click="toggle1(), dropAreas =! dropAreas">
      <span>Areas</span>
    </li>
    <li v-on:click="toggle2(), dropAdmin =! dropAdmin">
      <span>Administration</span>
    </li>
  </ul>
</div>
<!-- /menu -->
<!-- dropdowns-->
<div v-if="dropAreas">
  <ul>
    <li>
      <span>Kitchen</span>
    </li>
    <li>
      <span>Baths</span>
    </li>
  </ul>
</div>
<div v-if="dropAdmin">
  <ul>
    <li>
      <span>Profile</span>
    </li>
    <li>
      <span>Services</span>
    </li>
  </ul>
</div>
<!-- /dropdowns-->

This is the JavaScript code related to the functionality:

data () {
    return {
      dropAreas: false,
      dropAdmin: false
    }
  },
  methods: {
    toggle1 () {
      if (this.dropAdmin === true) {
        this.dropAdmin = false
      }
    },
    toggle2 () {
      if (this.dropAreas === true) {
        this.dropAreas = false
      }
    }
  }

*Please note that this code is being called in another component named "Home" like so:

<template>
  <div>
    <menu></menu>
    <!-- [...] -->
  </div>
</template>

If you have any manual solutions or ideas on how to achieve this functionality, I would greatly appreciate your input. Thank you.

Answer №1

If you're looking for a workaround, here's a solution that involves utilizing the tabindex HTML attribute along with the :focus CSS pseudo-class:

new Vue({

  el: '#app',
  template: `
    <div class="container">
      <div
      ref="menu"
      id="menu"
      tabindex="0"
      >Menu</div>
      <ul id="dropdown">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
      </ul>
    </div>
  `

});
#menu {
  display: inline-block;
  padding: 1em;
  border: 1px solid #e6e6e6;
  cursor: pointer;
}

#dropdown {
  display: none;
}

#menu:focus + #dropdown {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>

<div id="app"></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

Utilizing a created variable within the alert function: A guide

In order to display error messages in my app, I have created the following code: function createTimer(): void { if (!timer.start) { Alert.alert(strings.reminders['date-required']) return; } else if (!timer.end) { Alert.alert(strin ...

Display content exclusively in PDF format

On my HTML page, I have two sections - one for inputting values and the other for viewing a PDF. To ensure that the PDF view is hidden until explicitly requested, I need it to remain invisible by default. It should only appear as a PDF when someone clicks ...

Is there a way to narrow down Drive API list results based on a specific domain that has write permission?

I am currently working on retrieving a list of files from the drive API using a service account, with permissions granted to a specific domain for editing. While I have successfully implemented this feature for individual emails, I am facing a challenge in ...

Adding dynamically fetched JSON to an existing table

http://jsfiddle.net/mplungjan/LPGeV/ What could be improved in my approach to accessing the response data more elegantly? $.post('/echo/json/',{ "json": JSON.stringify({ "rows": [ { "cell1":"row 2 cell 1", "cel ...

How to implement a service function to handle $http responses in a controller

Is it possible to use $http only for my service and not the controller? I am getting undefined in my console.log when trying to display data in a $scope. Here is my code: app.controller('adminControl', ['$scope','$routeParams&apo ...

Encountered a login issue when attempting to access the localStorage

Any suggestions on resolving this error? Encountering a QuotaExceededError with DOM Exception 22 This issue arises when attempting to access the localStorage and assign data to the header. Currently working with Angular 2 on the client side using Type ...

Creating a drop-down menu within an HTML table along with a D3 bar chart

How can I implement a drop-down menu allowing the user to choose a time interval for this HTML table and d3 bar chart? The time intervals needed are: Now, 24 hours, 48 hours, 72 hours, 1 week, and 1 month. I am relatively new to creating dynamic tables and ...

JavaScript file isn't being called by index.html

I am working on establishing a basic client/server connection using node.js modules along with a straightforward HTML page. The content of the HTML page is as follows: <script type="text/javascript" src="index.js"></script> The index.js fi ...

Is there a way to determine the duration that a click was held down for?

When triggering an onClick event, I want to determine whether it was a single click or if the mouse button was held down for some time before releasing. This way, I can call the myTest() function within onClick="myTest()", which will log "mouse was click ...

Exploring an Array Based on User's Input with JavaScript

Looking to implement a search functionality for an array using AJAX. The array is pre-populated with values, and the user will input a value in a HTML text box. If the entered value is found in the array, it should display "Value found", otherwise "not f ...

Instructions for showing a timer on a webpage from a managed bean by utilizing JavaScript

I'm currently tackling the challenge of passing a Date from a managed bean to JavaScript and then displaying it as a timer in the format "hh:mm:ss aa". I've attempted it but so far, no luck. Code: DateTimeManagmentMB.java (Managed Bean) import ...

Using aliases in npm packages is not supported

I am working on creating an npm package that I want to use in another application. During development, I set a path in tsconfig for importing various modules instead of using a relative path. However, when I download my package into the test app, it is una ...

What is the best way to make an input text the focus when an item on a dropdown menu is clicked?

I have a website with a dropdown menu and an input box. I want the user experience to be more seamless by automatically focusing the mouse cursor inside the input box when they click on an option in the dropdown menu. This way, users can start typing right ...

Challenges in retrieving information from a two-dimensional JSON dataset

I am encountering an issue with a nested JSON structure. JSON: [{"id":"15", "rand_key":"", "landlord_name":"Shah", "property_req_1":{ "lead_req_id":"", "lead_id":"0", "category_id":"1", "region_id":"1", "area_location_id":"17", ...

Is it possible to modify the font size of all text that shares a particular font size?

Lately, I've been pondering on a question. A few years ago, I created a website using regular CSS and now I want to make some changes to the font sizes. While I know that CSS variables are the recommended solution for this situation, I'm curious ...

AngularJS has encountered an error due to exceeding the maximum call stack size limit

Utilizing AngularJS and a web API, I am fetching data from an SQL table. I have designed a function that populates input fields with values when a row is selected from an HTML table. However, I encountered an error during debugging when clicking on any row ...

Utilize MetroUiCSS to effortlessly integrate a sleek calendar into your AngularJS application

I'm looking to incorporate a calendar from Metro Ui CSS into my project. Here is the link to the calendar: However, I am struggling with how to activate the calendar. I have already included all necessary scripts in my index.html (3 scripts) and have ...

Adjust the height of an element using CSS based on the height of another

Is there a way to have two divs per row, where the second div always displays its full content and the height of the first div matches the height of the second div? If the content in the first div exceeds the height, it should be scrollable. I've atte ...

Utilizing the Filter Function to Eliminate an Element from an Array

I am a beginner in the world of React and I'm currently working on developing a simple timesheet tool where users can add tasks and save them. My tech stack includes React and Typescript. Currently, my main component has an empty array for tasks and ...

Create a canvas and include input boxes in an HTML document

I'm attempting to create a canvas line diagonally above two textboxes that are also positioned diagonally (similar to Samsung's pattern passcode) when a button is clicked, but I am facing difficulties in achieving this. I have attempted to solve ...