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

The ion-range slider does not function properly when trying to display a central label

After customizing the ion range slider to suit my needs, I am looking for some simple functionalities: 1. The label should be centered. 2. When clicking on the label, the handle should move accordingly. 3. There should be a color gap between two valu ...

Locate the element for a button or an image

Having trouble recognizing the object in the image. Looking for guidance on how to identify the Button using ClassName or customized XPATH. <div class="schedule"> <a href="https://link" target="_blank"> <img border="0" alt="Sc ...

Looking for a resolution? Ensure that actions are plain objects by employing custom middleware specifically designed for managing asynchronous actions

I'm attempting to replicate a MERN stack project named Emaily, but I've encountered an error Error: Actions must be plain objects. Use custom middleware for async actions. Here is the code for my Action: import axios from 'axios'; im ...

The single controller can now showcase various notification styles for operations such as insertion, updating, or error handling

I need to display notifications to the user based on three different scenarios using a controller. When data is successfully inserted When data is successfully updated In case of an error For each scenario, I want to show a different style of notificati ...

Adjust the image's placement and reduce its size as the screen size decreases, without using any media queries

Essentially, I encountered an issue where I had a table row with 2 cells - the left cell containing text and the right one containing an image. As the screen size decreased, I needed the image to move below the text. After some investigation, I delved into ...

Is employing absolute paths in our confidential Node dependencies a good idea?

I have recently organized our codebase's React components into a separate dependency to make them reusable across different projects. To improve readability, all components now utilize Webpack aliases: import TestComponent from 'components/TestCo ...

The issue with Angular 4 imports not refreshing in a .less file persists

Currently, I am in the process of developing a small Angular project that utilizes less for styling purposes. My intention is to separate the styling into distinct folders apart from the components and instead have a main import file - main.less. This fil ...

The Autocomplete feature in Material-UI is not rendering any output

Within the render method of a class, an Autocomplete component is causing nothing to appear as rendered; once removed, everything else renders as expected. export default class Home extends Component { render() { return ( ... ...

Tips for arranging Radio buttons in multiple columns within the same Radio group in Material UI

As a newcomer in the world of React.js, I am feeling a bit anxious about posting my question on Stack Overflow. I hope everyone can overlook my lack of experience and forgive me for any mistakes. I have been struggling to find the right solution to my prob ...

Improving an HTML list with JavaScript

My current project involves a JavaScript game similar to Scrabble. I want users to be able to create new words in the game, and have those words added to a list that is displayed on the page within a div element. However, I'm struggling to understand ...

The antithesis of jQuery's .parents() selector

I am currently developing a userscript for a webpage with an old-fashioned design consisting mainly of tables. My goal is to access a long table of fields so that they can be filled in automatically by the script. To simplify, the structure is as follows: ...

Specify the location of the resize button (corner)

Scenario : At the bottom of the page, there is a resizable textarea, However, having the resize button at the bottom-right corner does not provide the best user experience (try it out), Issue : I am wondering if there is a way to move the resize butt ...

The PHP script is failing to send out email notifications

I am facing an issue with my website's contact form that is supposed to send out an email after the user fills it out and clicks submit, but it does not appear to be working. Unfortunately, I do not have access to the mail server since it is hosted e ...

Utilizing HTML and CSS to Position Text Adjacent to the Initial and Final Elements in a Vertical List

Exploring a simple number scale ranging from 1 to 10, I experimented with different ways to represent it. Here's my attempt: <div class="rate-container"> <p class="first">Extremely Unlikely</p> <a class=" ...

The conditional comment designed for browsers other than Internet Explorer may not work properly on outdated versions of

I find myself in a predicament where I must dynamically load one of two stylesheets depending on the browser accessing the page: If any browser other than IE, then load the "new" stylesheet If IE is version 9 or higher, then load the "new" stylesheet ...

Unlock the Power of Core 2 MVC with the Cutting-edge Integration of

Looking for a solution on how to effectively use JQuery Datatables with Core MVC? Check out this helpful resource: Using jQuery DataTables Grid With ASP.NET CORE MVC I recently downloaded the sample project and made some modifications to fit my needs. It ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

External JavaScript file not executing defined function

My homepage includes a register form that should open when the register button is clicked. However, I am encountering an issue where the function responsible for opening the form from another JavaScript file is not being triggered. Here is the HTML code: ...

Exploring the implementation of the meta robots tag within Joomla 2.5's global settings

Encountering a peculiar issue with Joomla 2.5 and the Meta robots tag. Joomla seems to have a flaw where regardless of the URL, as long as there is a valid article id, it will generate a page. For instance: The id '61' is valid but leads to a ...

What is the best way to use border radius on a canvas element similar to a div in order to create a

I'm having trouble making a canvas element appear as a circle like any other div. Here is my code, please take a look and let me know what I'm doing wrong with the border-radius property: <canvas id="myCanvas" width="200" height="200" style ...