Utilize the `addEventListener` and `removeEventListener` functions on the menu to

Why is my mobile menu not functioning correctly? The submenu should open on the first click and redirect to the parent URL on the second click, which works fine. However, when the window width increases to 768px or more, the submenu should appear on hover over the parent but the parent tag doesn't redirect properly on the first click.

I need assistance in reorganizing the window.addEventListener('resize', function(){ ... }); as the addEventListener and removeEventListener functions are not working as expected.

Why does the event triggering the prevFirstClick (mobile version) function remain even after enlarging the screen to 768 px?

And why isn't the event triggering the prevFirstClick (desktop version) function added back when the screen size is reduced below 768 px?

I've tried numerous combinations without success. Any guidance would be greatly appreciated!

Answer №1

Give this a try:

document.addEventListener('DOMContentLoaded', function() {
  const menuItems = document.querySelectorAll('.menu-item-has-children');

  function mobileClickHandler(event) {
    let isOpen = this.getAttribute('aria-expanded') === 'true';

    if (!isOpen) {
      this.setAttribute('aria-expanded', 'true');
      event.preventDefault(); // Prevent navigation on first click
    } else {
      this.setAttribute('aria-expanded', 'false'); // Reset for next click
    }
  }

  function addMobileEvents() {
    menuItems.forEach(item => {
      item.addEventListener('click', mobileClickHandler);
    });
  }

  function removeMobileEvents() {
    menuItems.forEach(item => {
      item.removeEventListener('click', mobileClickHandler);
      item.setAttribute('aria-expanded', 'false'); // Reset menus when switching to desktop
    });
  }

  // Set up event listeners based on initial width
  if (window.innerWidth < 768) {
    addMobileEvents();
  }

  window.addEventListener('resize', function() {
    if (window.innerWidth < 768) {
      addMobileEvents();
    } else {
      removeMobileEvents();
    }
  });
});

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

Cease making commitments or declarations

I am currently working on validating an image using an API. I have implemented promises and want the execution to stop and call a function if the API check fails. Here is my code: The function for calling the promises: checkPhotos(options,formData, "fr ...

Properly appears in Chrome, but experiences issues in Internet Explorer 11

The design of the website looks seamless in Chrome and Firefox, however, when I view it in Internet Explorer, I notice a significant gap on the right side of the first two pages. How can I fix this issue specifically for Internet Explorer? Should I use a m ...

Tips on determining if a string is a properly formatted HTML:

My question is about checking whether selected strings in a web form are valid HTML syntax. How can I achieve this on a button click? function chkhtml() { var code = $("<table><td>"); code.each(function () { if( ...

Chrome Flexbox Hacks: Controlling the Size of Nested Items

How can I ensure that an element nested within a flexbox member in Google Chrome is limited to the size of its container? For example, consider the following scenario: <div style="display:flex; flex-direction:column; height:100vh;"> <div style= ...

JS: I'm struggling to understand the scope

I've been working on adapting CouchDB's JS API to function asynchronously, but I'm encountering an unresolved error: You can find my version of the JS API here on Pastebin. Whenever I execute (new CouchDB("dbname")).allDocs(function(result) ...

Displaying a submenu upon hovering within its designated CSS region

I'm encountering an issue with my submenu. It's supposed to appear when hovering over the parent menu li, but it also shows up when the mouse hovers over its area. Let's take a look at some images. First screenshot below shows that it works ...

Could there be a glitch affecting the alignment of the dropdown-menu-end in Bootstrap 5.0?

I can't seem to make dropdown-menu-end from Bootstrap 5.0 work in Angular, even though I copied the exact code from https://www.w3schools.com/bootstrap5/bootstrap_dropdowns.php. The HTML display using my code from VSC looks like this: site appearance ...

React - Obtain User Login Details and Verify

I am working on a React project that includes a Login Form. The code has been organized into small components for reusability, but I am unsure of how to retrieve and validate user credentials (username and password). Is there a method available to validate ...

When a cookie is set in NextJS with a static export, it reverts back to its original

My current project involves building a multilingual website. To handle language selection, I have implemented a system where the chosen language is stored in a cookie and retrieved using getInitialProps in the _app file, which is then passed as a context A ...

Troubleshooting tip for React JS: encountered an unexpected object error when trying to import components

I've been working on building a react app with Create React App, and everything was going smoothly until I encountered a frustrating error message: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

Adjusting the Aspect Ratio of an Embedded YouTube Video

<!DOCTYPE HTML> <head> <style> body { overflow: hidden; margin:0; } </style> </head> <body> <iframe id="video" src="https://www.youtube.com/embed/U4c9bBeUe4M?modestbranding=1&sh ...

Tips for enlarging the box width using animation

How can I create an animation that increases the width of the right side of a box from 20px to 80px by 60px when hovered over? What would be the jQuery code for achieving this effect? ...

Generate slanted projection mapboxgl

Trying to develop a building simulator based on zoning codes. I can measure values, create floors, but struggling to extrude diagonally or create a perpendicular plane to the floor for evaluating angles from the street to limit building height (see image 2 ...

An issue arises with ReactJS MaterialUI Stepper when there is an overflow

My struggle with the Material UI Stepper component persists as I attempt to make it suit my requirements, specifically to display multiple steps and handle overflow. However, it stubbornly continues to misbehave by showing unusual separators when there is ...

Implementing dynamic props in Vue2 component by passing arbitrary named variables

Having recently delved into Vue, I am facing a challenge that has left me scratching my head after consulting the documentation: I am struggling to pass an arbitrarily named variable as a prop to a component instance. As per my understanding, props serve ...

setting different iframe widths for desktop and mobile views

I am working with an iframe and facing a challenge. I want to make it full screen width on mobile devices, but only half the screen width on a normal monitor (100% and 50%, respectively). The minimum specification for the mobile device would be iPhone, alt ...

How to clear input fields in Ant Design ReactJS components

Utilizing the form list component from antd in my react.js project https://ant.design/components/form/#Form.List I have a basic form list set up where I can easily add or remove fields. At times, I need to reset the form and remove any additional items t ...

Using Node-twitter within the Express framework

I'm currently exploring the node-twitter module within the express framework. Although I have a basic understanding of node, including routing, rendering jade templates, and installing packages, I find myself overwhelmed by the sheer number of package ...

Tips for effectively implementing an Ajax request with JavaScript when the page loads

I have been developing a shopping cart application that utilizes local storage to store the items added by users. The challenge I'm currently facing is populating the page with the user's cart items stored in local storage when they navigate away ...

What is the best way to dynamically change the color of my component depending on the prop passed to it?

I am facing an issue with the color of my component changing based on the value of the prop 'level'. Despite using states to set the backgroundColor, all components end up having the same color due to the state being altered for every comment. I ...