How can I automatically close the menu when I click on a link in Vue?

  1. Tap the menu icon
  2. Select a link
  3. The URL changes in the background.
  4. However, the menu remains open. How do I close the menu when a link is selected? The menu is wrapped in a details HTML element.

Is there a way to remove the "open" attribute from the details?

I would appreciate simple suggestions, as I am a designer with limited knowledge of JavaScript. Thank you!

Below is my code for the navigation:

    <details>
        <summary class='menu'>
          <div class='line line1'></div>
          <div class='line line2'></div>
          <div class='line line3'></div>
        </summary>
        <div class='dropdownMenu'>
          <div class='column'>
            <label>Categories</label>
            <a class='link' href='/category1'>Category 1</a>
            <a class='link' href='/category2'>Category 2</a>
            <a class='link' href='/category3'>Category 3</a>
          </div>
          <div class='column'>
            <label>Contact Us</label>
            <a class='link' href='mailto:info@example.com'>info@example.com</a>
            <a class='link' href='tel:1234567890'>(123) 456-7890</a>
          </div>
        </div>
      </details>
    

Answer №1

To enhance the functionality of your Vue Router, consider implementing a Global Navigation Guard. By using native HTML for menu control, you'll need to locate and eliminate the presence of the open attribute, which dictates the open/closed state within the <details> tag.

const router = new VueRouter()

router.beforeEach(() => {
  document.querySelector('details').removeAttribute('open')
})

Answer №2

To make things easier for yourself, consider assigning a class to all the links such as 'link closebar-remove' and include it in your JavaScript code.

The term 'show-menu' mentioned after the toggle refers to a placeholder value in your CSS. You will need to specify this value based on the CSS elements related to the appearance of menuSlide.

const closeBar = document.querySelector('.closebar-remove');
const dropMenu = document.querySelector('.menuSlide');

closeBar.addEventListener('click', function(){
    dropMenu.classList.toggle('show-menu');
});

If the dropMenu.classList.toggle method doesn't work as expected, you can try using dropMenu.classList.remove('appropriate-css-class')

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

Having npm start is causing an error to be displayed

I am encountering an issue when I try to start 'npm' on my mean.js application. The error message is related to a missing file called '.csslintrc'. Below, I have included the terminal output as well as the snippet of code where the erro ...

Arrangement of 'const' variables within React Stateless Components

Consider a scenario where I have a straightforward React stateless component: const myComponent = () => { const doStuff = () => { let number = 4; return doubleNumber(number); }; const doubleNumber = number => { ...

What is the term used for the objects that res.render passes?

I constantly find myself struggling with defining objects inside res.render. Is there a way to define them globally or outside of res.render? I hope someone can offer some guidance.. here is a sample code snippet: router.get("/home/blog", function(req,r ...

Using JavaScript and jQuery to calculate the time difference between two values

Here is a code snippet for calculating the difference between two numbers: function calculateDifference(num1, num2) { if (num1 > num2) { return num1 - num2; } else { return num2 - num1; } } On document.ready event: var result = calculateD ...

What is the best way to reach the parent controller's scope within a directive's controller?

In a scenario where I have a custom directive nested inside a parent div with a controller that sets a variable value to its scope, like this: html <div ng-controller="mainCtrl"> <p>{{data}}</p> <myDirective oncolour="green" ...

Receiving the error message "Encountered SyntaxError: Unexpected token )" when using a custom directive

Encountering an issue with the customer directive of auto-complete, as I am receiving the error Uncaught SyntaxError: Unexpected token ). This error is displayed in the console of the chrome browser as VM80623:1 Uncaught SyntaxError: Unexpected token ). Cl ...

Toggle the visibility of the password using VueJS without changing the value of the "type" property

I have been working with a basic input component that includes the property type, which has been functioning well so far. However, I am facing some challenges when trying to implement password obfuscation. How can I toggle the visibility of the password w ...

I am looking to obtain a value through a JavaScript function that sums values upon clicking. The result is satisfactory, but I am seeking a way to limit the value

I only need 2 decimal values, not large ones. Can someone please help me achieve this? <script> $(function() { $("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown ke ...

Retrieving the vue-router path URL from a $route object in Vue 1.x/2.x

It's common knowledge that vue-route can be utilized to encapsulate certain route paths. <!-- vue 1.x --> <a v-link="{name: 'route_name', params: {id: 1}}"></a> Transitioning to vue2: <!-- vue 2.x --> <router-li ...

Preserve a data point without causing any alterations

I am working with a device that continuously sends values until it is stopped. These values are then saved inside an array. deviceMonitoring( device2 ){ // In this function, I populate the arrayTimestamp and then copy the first value. this.arrayElement = t ...

Struggling with mapping through a multidimensional array?

I'm facing an issue with using .map() on a nested array. I initially tried to iterate through my stored data using .map(), and then attempted another iteration within the first one to handle the nested array, but it didn't work as expected. The ...

How to pass a variable or value through the async await API in the Vue.js and Laravel integration?

I'm facing an issue with my API where I want to check if a given email exists in the database, but every time I run it and view the console log, it returns undefined. Can anyone here suggest a better code snippet or approach for this? I specifically w ...

How can you stop queuing animations and timeouts in jQuery?

I'm facing a seemingly simple problem that I need help with. On my website, there's a hidden div.notification bar at the top. This bar can be displayed by adding either the success or warning class to it. There are two scenarios: either a messa ...

React is failing to display identical values for each item being mapped in the same sequence

I have implemented some standard mapping logic. {MEMBERSHIPS.map((mItem, index) => ( <TableCell className="text-uppercase text-center" colSpan={2} padding="dense" ...

Incapable of modifying the inner content of a table

I am completely new to AngularJS and struggling with updating the inner HTML of a table. I have a variable that contains a string with three types of tags: strong, which works fine, and nested tr and td tags. However, when I try to replace the table's ...

The res.send() method in Restify was not triggered within the callback function of an event

Currently, I am utilizing restify 2.8.4, nodejs 0.10.36, and IBM MQ Light messaging for a RPC pattern. In this setup, when the receiver has the result ready, it emits an event. The below restify POST route is supposed to capture this event along with the ...

Unable to verify the provided resource: Mailchimp

Welcome everyone to my first question posted on StackOverflow. I have tried my best to provide all the necessary details regarding the issue in order to seek assistance. If you require additional information, feel free to ask. To give a brief overview, I ...

Sending the array data to the component and executing it

Trying to familiarize myself with Vue2, but I am having issues with the "markers" array not updating on the map. How can I make this array reactive and ensure that the map markers change accordingly? Thanks for any assistance! views/Map.vue <template ...

The HttpParams are reluctant to be established

Working with Angular 8, I am attempting to assign an HttpParam using the provided code snippet and observing the outcome on the final line. let newParams = new HttpParams(); newParams.set('ordering', 'name'); console.log('getting: ...

What steps do I need to take to ensure that this Regex pattern only recognizes percentages?

I am attempting to create a specific scenario where I can restrict my string to three digits, followed by a dot and two optional digits after the dot. For example: 100.00 1 10.56 31.5 I've developed a regex pattern that allows me to filter out any ...