Ensure that when you click on the next dropdown menu opener button, the previous dropdown menu closes and only the new menu remains open

Take a look at this page first to get an understanding:

On this page, I have implemented multiple dropdown menus that should open when clicked on their respective opener buttons (3 bar icon) and close either when clicked again or anywhere else on the page.

Currently, the menus open when clicked but do not close if another menu is clicked without closing the previous ones. This results in all three menus being opened simultaneously, which is not the desired behavior.

The goal is to have only one menu visible at a time. When a new menu is clicked, it should open while closing any previously opened menu. This should work seamlessly across multiple copies of the HTML code without requiring specific IDs.

The solution needs to be implemented using pure JavaScript and should allow for dynamic functionality with no limitations on copying and pasting the code.


<!DOCTYPE html>
<html lang='en-US'>

<head>
  <title>au2p10</title>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1'>

  <style>
    /* Styling */
  </style>
</head>

<body>
  <!-- Menu Items -->
  <div class='res-loc-shre-con'>
    <!-- Menu Content -->
  </div>

  <!-- Script Section -->
  <script>
    // JavaScript Logic
  </script>

</body>

You can download the full HTML file from this link for testing and further examination: . Feel free to reach out if you need clarification on any part of this request.

Answer №1

Try using this new eventlistener code:

window.addEventListener('click', function(event) {
    var dropDownMenus = document.getElementsByClassName('drop-down-menu');
    for (var k = 0; k < dropDownMenus.length; k++) {
      var openDropDownMenu = dropDownMenus[k];
      if (openDropDownMenu.classList.contains('show-drop-down-menu') && event.target.closest('.menu-icon') !== openDropDownMenu.parentElement) {
        openDropDownMenu.classList.remove('show-drop-down-menu');
      }
    }
});

This revised code ensures that when clicking on a menu, it will close any other open menus except the one that is being clicked on.

Additionally, as mentioned by Dennis, make sure to have the eventlistener function separated from any other functions for proper functionality.

Answer №2

Design a function to close all menu items whenever any menu is clicked (you've already tackled that part). Then proceed to open the specific menu.

function closeAllMenus() {
    var editMenuDropdowns = document.getElementsByClassName('edit-menu-drop-down-box');
    for (var j = 0; j < editMenuDropdowns.length; j++) {
      var openEditMenuDropdown = editMenuDropdowns[j];
      if (openEditMenuDropdown.classList.contains('show-edit-menu-drop-down-box')) {
        openEditMenuDropdown.classList.remove('show-edit-menu-drop-down-box');
      }
   }
}

In addition, it seems like there's a missing curly brace at the end of your show_edit_menu_dropdown_box function.

Answer №3

Remember to close all menu options before opening a new one.

To ensure this, include the following lines in your code:

function show_edit_menu_dropdown_box(e) {
// Ensure all menus are closed
var cards = document.querySelectorAll(".edit-menu-drop-down-box");
 cards.forEach(item => {
      item.classList.remove("show-edit-menu-drop-down-box");
});

var card = e.target.closest('.edit-menu-icon-con');
var edit_menu_dropdown_box = card.querySelector('.edit-menu-drop-down-box');
edit_menu_dropdown_box.classList.toggle('show-edit-menu-drop-down-box');

window.addEventListener('click', function(event) {
  if (!event.target.matches('.edit-menu-icon-image')) {
    var editMenuDropdowns = document.getElementsByClassName('edit-menu-drop-down-box');
    for (var j = 0; j < editMenuDropdowns.length; j++) {
      var openEditMenuDropdown = editMenuDropdowns[j];
      if (openEditMenuDropdown.classList.contains('show-edit-menu-drop-down-box')) {
        openEditMenuDropdown.classList.remove('show-edit-menu-drop-down-box');
      }
    }
  }
});

}

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

Executing a Component function within an "inline-template" in VueJS

VueJS version 1.9.0 app.js require('./bootstrap'); window.Vue = require('vue'); Vue.component('mapbox', require('./components/mapbox.js')); const app = new Vue({ el: '#app' }); components/mapbox.js ...

How to utilize Vue method for accessing DOM elements

I'm working on a container with various elements like h1, p, etc. The container has a background and I'm trying to create a method to move it based on mouse coordinates. However, I'm facing an issue where the e.target is showing me ele ...

Exploring Elasticsearch: Uncovering search results in any scenario

I've been working on a project where my objective is to receive search engine results under all conditions. Even if I enter a keyword that is not included in the search data or if it is an empty string, I still want to get some kind of result. How can ...

Get a reference to pass as an injection into a child component using Vue js

Is there a way to pass a reference to child components? For example: The Parent component provides the ref: <template> <div ref="myRef" /> </template> <script> export default { name: 'SearchContainer', pr ...

A pair of demands within an express service

Currently, I'm facing an issue in a project where I am attempting to create a service using Express that makes two external API calls. However, I am encountering an error in Express that is difficult to comprehend. It seems like my approach might be i ...

Encountering a problem with npm installation during the setup of node-sass

While attempting to run the npm install command, I encountered an error during the installation of node-sass. https://i.stack.imgur.com/qcDaA.png https://i.stack.imgur.com/YxDi2.png Here is my package.json file: { "name": "XXXXX", ...

What is the best way to paginate aggregated results in Mongoose?

In my project, I have a User model that is linked to two other associated models - Profile and WorkProfile. The Profile model contains basic information about the user like name, email, and home address, while the WorkProfile model stores details such as o ...

Using three.js to input text instead of particles within a particle cloud

I have a unique three.js codepen project where square particles drift through the space. However, I am now looking to enhance it by incorporating text (perhaps using geometry?) instead of the square particles, creating a word/tag cloud effect. Is this eve ...

The reducer and the store are experiencing a lack of synchronization

I'm having trouble figuring out what's going on with my json file that contains a list of products. I'm trying to render specific ones, but it's not working as expected. Here's the reducer code I'm using: export default(stat ...

[Vue alert]: Issue with rendering: "TypeError: Unable to access property 'replace' of an undefined value"

I'm currently working on a project similar to HackerNews and encountering the following issue: vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot read property 'replace' of undefined" found in ---> <Item ...

using jQuery to show a block element

I'm attempting to determine whether a div with the style display as block then perform an action. Here is an example: This is just an idea I'm trying to implement using jQuery. if ($("#toshow").css("display") == "block"){ }else{ } ...

Guide to organizing a one-to-one object map within Angular JS ng-repeat

Is there a way to organize a one-to-one object map in angular.js using filters (or any other technique) while working within an ng-repeat loop? This is what I currently have: obj:{ a:3, c:5, d:1, g:15 } Basically, I want to achieve s ...

What is the more effective option: utilizing the bootstrap offset feature or inserting an empty div?

<div class="col-xs-3"></div> <div class="col-xs-6 col-sm-6 col-md-6" style="min-width: 320px;"> </div> OR <div class="col-xs-6 col-md-offset-3 col-sm-offset-3 " style="min-width: 320px;">` </div> I would like to remo ...

What orientation is best for the back arrow to take in a website written in Arabic?

Currently developing a website that supports Arabic language while considering security measures. The browser's back button will terminate the session, requiring users to utilize the on-page back button instead. When incorporating Arabic text, should ...

Filter the specific output in a generator function

I have a code snippet that I need help with. function* iterateRecord() { const db = yield MongoClient.connect(''); const collection = db.collection(''); const query = {} const cursor = collection.find(query); ...

The website is unresponsive to the media query

Currently, I am working on a project using Windows 10, Codeigniter, jQuery, and Firefox 43.0.4. However, I am facing an issue that is quite baffling to me. My goal is to apply styles specifically for an iPad-sized window, so I have implemented the followin ...

What is the best way to handle promises within the context of updating state in React

Recently, I've been working on a React code snippet focused on creating a text input field. onChangeDestination(url, index) { this.setState(prevState => { const rules = [...prevState.rules]; rules[index] = { ...rules[index], url}; ...

Grid system not being followed by table in Bootstrap layout

I'm struggling to figure out why the table I have doesn't follow Bootstrap's grid system. It took me a good 2 hours to pinpoint and fix the issue. Any help would be greatly appreciated. I could share the code, but it might be easier for you ...

Combining round brackets and square brackets when initializing an array

In the snippet below, values are assigned with a mix of parentheses and square brackets without any errors. However, most other combinations (such as parentheses inside square brackets) do not work at all. var myItems = []; myItems[5] = ("A1", "B1", ["C1" ...

The output from the Compute function is not showing up in the TextBox as expected

I'm currently working on an HTML page that contains two textboxes and a button. I've created a Compute function to display the result in one of the textboxes, but unfortunately, it's not functioning as expected. No alerts are appearing on th ...