Bind event listener exclusively for click event handlers

I have a scenario where I am using 'addEventListener' to handle the opening of a menu (genres-container) only after the transition on another menu (mobile-nav) has completed. The issue I am facing is that even after closing everything and trying to reopen mobile-nav, 'addEventListener' seems to trigger, even if I haven't clicked on genres-container. What I am looking for is a way to reset everything when I close mobile-nav.

function handleMenu() {

  var genresMenu = document.getElementById('genres-container');
  var mobileMenu = document.getElementById('mobile-nav');

  // If genres-container is open, close it.
  if (genresMenu.className === 'nav-active') {
    genresMenu.className = 'nav-disabled';
    mobileMenu.className = 'nav-disabled';
  }

  // Else, open or close mobile-nav.
  else {
    if (mobileMenu.className === 'nav-disabled') {
      mobileMenu.className = 'nav-active';
    } else {
      mobileMenu.className = 'nav-disabled';
    }
  }
}

function handleGenres() {

  var mobileMenu = document.getElementById('mobile-nav');
  var genresMenu = document.getElementById('genres-container');

  // If mobile-nav is open, close it.
  if (mobileMenu.className === 'nav-active') {
    mobileMenu.className = 'nav-disabled';

    // Wait for transition to complete.
    let element = document.getElementById("mobile-nav");
    element.addEventListener("transitionend", function(event) {

      // If genres-container is closed, open it.
      if (genresMenu.className === 'nav-disabled') {
        genresMenu.className = 'nav-active';
      }

      // Else, close it.
      else {
        genresMenu.className = 'nav-disabled';
      }
    }, false);
  }
}
.nav-disabled {
  max-height: 0;
  overflow: hidden;
}

.nav-active {
  max-height: 150px;
  overflow: hidden
}

#mobile-nav {
  transition: max-height ease .4s;
}

#genres-container {
  transition: max-height ease .4s;
}
<a class="nav-link" onclick="handleMenu()">menu</a>
<div id="mobile-nav" class="nav-disabled">
  <a class="nav-link" onclick="handleGenres()">genres</a>
</div>
<div id="genres-container" class="nav-disabled">
  genres menu
</div>

Answer №1

To prevent the event listener for `transitionend` from being added multiple times, it is important to move it outside of the `onClick` function.

 var x = document.getElementById('mobile-nav');
  var y = document.getElementById('genres-container');
 var isMenuTransition = false;
function menu() {
   isMenuTransition = true;


  // If genres-container is open, close it.
  if (y.className === 'nav-active') {
    y.className = 'nav-disabled';
    x.className = 'nav-disabled';
  }

  // Else, open or close mobile-nav.
  else {
    if (x.className === 'nav-disabled') {
      x.className = 'nav-active';
    } else {
      x.className = 'nav-disabled';
    }
  }
}
let element = document.getElementById("mobile-nav");
    element.addEventListener("transitionend", function(event) {
      if(!isMenuTransition){
      // If genres-container is closed, open it.
      if (y.className === 'nav-disabled') {
        y.className = 'nav-active';
      }

      // Else, close it.
      else {
        y.className = 'nav-disabled';
      }
      } else {
        isMenuTransition = false;
      }
    }, false);

function genres() {

 

  // If mobile-nav is open, close it.
  if (x.className === 'nav-active') {
    x.className = 'nav-disabled';

    //Wait for transition to be over.
    }
}
.nav-disabled {
  max-height: 0;
  overflow: hidden;
}

.nav-active {
  max-height: 150px;
  overflow: hidden
}

#mobile-nav {
  transition: max-height ease .4s;
}

#genres-container {
  transition: max-height ease .4s;
}
<a class="nav-link" onclick="menu()">menu</a>
<div id="mobile-nav" class="nav-disabled">
  <a class="nav-link" onclick="genres()">genres</a>
</div>
<div id="genres-container" class="nav-disabled">
  genres menu
</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

Is it possible to input rendered HTML into a vue property?

I am currently utilizing vue-material and running into the following situation: <md-dialog-confirm :md-active="true" md-title="Make an Outbound Call" md-confirm-text="Agree" md-cancel-text="Disagree" md-content="some <p>HTML ...

MUI: Autocomplete cannot accept the provided value as it is invalid. There are no matching options for the input `""`

https://i.stack.imgur.com/KoQxk.png Whenever I input a value in the autocomplete component, an unresolved warning pops up... Here's how my input setup looks: <Autocomplete id="cboAdresse" sx={{ width: 100 + " ...

"Discover the steps to efficiently utilize the lookup feature with array objects in MongoDB

I am a beginner with MongoDB and I am trying to create a schema for my collection as shown below please note that all ObjectId values are placeholders and not real stockIn documents { serial:"stk0001", date:'2021-06-11', productInTra ...

Leveraging Jquery and an API - restricted

I have the opportunity to utilize a search API that operates on JSON format through a URL GET. This particular API has a reputation for imposing quick bans, with an appeal process that can be lengthy. If I were to integrate this API into my website using ...

Using Javascript to Highlight a Single Row in a Table

Greetings esteemed members of the skilled community at StackOverflow, I must humbly ask for your expertise in solving a dilemma that I am currently facing. The situation is as follows: I have a table generated from an SQL query, and it is crucial for the ...

Error message "Unexpected token" occurs when attempting to use JSON.parse on an array generated in PHP

My attempt to AJAX a JSON array is hitting a snag - when I utilize JSON.parse, an error pops up: Uncaught SyntaxError: Unexpected token Take a look at my PHP snippet: $infoJson = array('info' => array()); while($row = mysqli_fetch_array($que ...

Using Jquery to manipulate arrays based on options selected from a dropdown menu

I am currently working on a feature that suggests tags based on the selected category. This involves using a select box to choose a category and then displaying sub-categories in a list. Here is the current setup: <select id="categorySelect"> < ...

Stunning Opening and Closing Animation with Ajax

Looking for help with creating an animation like the one shown here: Incorporating this into my current site at: dageniusmarketer.com/DigitalWonderland/ I want the window displaying text content to open and close as users navigate through the links, ess ...

The function `splitPinCodes.split(',')` is causing a malfunction

I am encountering an issue with validating the input data. The input text area should contain 6-digit zip codes separated by commas. I have implemented the ng-change="convertToArray()" method in Angular for the input text area. If I enter more than 6 digi ...

Arrange pictures and hyperlinks on an image

I am trying to add links to an image, similar to what Wikipedia does with the map of Germany and its states. Back in the 90s, I would have used the map tag for this purpose. After examining the source code of the map on Wikipedia, I noticed that all the s ...

Including an identical field within the parameters of a MongoDB search query

In my mongodb collection testdata, there is a field named insertTime. Our goal is to remove data older than 60 days. Previously, to accomplish this, I would use the logic of finding the deletion date and then comparing it against the updateTime: var date = ...

Sharing images on a web app using Express and MongoDB

My objective is to develop a portfolio-style web application that allows administrators to upload images for other users to view. I am considering using Express and MongoDB for this project. I am uncertain about the best approach to accomplish this. Some ...

Can someone help with the issue where the CSS field position changes when the "X" icon appears, as mentioned in the title? I am looking for a solution to fix this problem

https://i.sstatic.net/Cj8Bm.pngWhen trying to add an additional field on a page, the "X" icon appears inline with the field and causes the other fields to adjust their position. However, I want the new field to remain in the same position as the title. How ...

Using Angular and Jasmine: techniques for simulating a service that provides a promise

In my AngularJS application, I have a controller called MenuCtrl that utilizes a service provided by "$mdSidenav" from Angular Material. This service is created using a factory method. angular.module('leopDirective', []) .controller('Me ...

Receiving an empty string from Chrome FileReader when dealing with large files (300MB or more)

Objective: The task is to read a file from the user's file system as a base64 string in the browser The size of these files can be up to 1.5GB Challenge: A script that works flawlessly on Firefox, regardless of the file size On Chrome, the script p ...

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

Automated system is responsible for flagging and disabling comments

We are facing a puzzling issue at the moment. Our comments form allows users to submit their thoughts on news articles, and each submission is immediately accepted and displayed on the same page. Within each comment, there is a link that enables users to ...

My jquery is malfunctioning when trying to retrieve values

I am facing an issue with accessing server-side values in my jQuery function. When I use my localhost path (NewsRecord.php) as the AJAX URL, it works fine. However, when I use the server path, it does not work. The strange thing is that the server URL pr ...

Step-by-step guide to importing a directory in ReactJS

Is there a way to create an input that can upload an entire directory with all its folders intact? I attempted the following code: <input ref={wrapperRef} id="file-upload" name="file-upload" type="file" ...

Updating a string in JavaScript by dynamically adding values from a JSON object

In my current function, I am making a request to fetch data and storing it as an object (OBJ). Afterwards, I make another request to get a new URL that requires me to update the URL with values from the stored data. The information saved in the object is ...