Collapse dropdown menus upon clicking outside of them

As a newcomer to coding, I'm trying to figure out how to create multiple dropdown menus where each one collapses when you click outside of it. I've been struggling with the code I wrote for weeks now - I want to have 3 dropdown menus but only one is working properly. Can someone help me fix this issue? Thank you in advance!

    HTML Code

    <div class="container">
      <a href="#home"><span class="Agencymenu">Home</span></a>
      <a href="#news"><span class="Agencymenu">News</span></a>
      <div class="dropdown">
        <button class="dropbtn" onclick="myFunction()">Team 1</button>
        <div class="dropdown-content" id="myDropdown">
          <a href="#"><span class="Agencymenu">Link 1</span></a>
          <a href="#"><span class="Agencymenu">Link 2</span></a>
          <a href="#"><span class="Agencymenu">Link 3</span></a>
        </div>
      </div> 
      <div class="dropdown2">
        <button class="dropbtn2" onclick="myFunction2()">Team 2</button>
        <div class="dropdown-content2" id="myDropdown2">
          <a href="#"><span class="Agencymenu">Link 1</span></a>
          <a href="#"><span class="Agencymenu">Link 2</span></a>
          <a href="#"><span class="Agencymenu">Link 3</span></a>
        </div>
      </div> 
    </div>

CSS Code
   (Same as original)

JS Code:  
(Same as original)

Answer №1

For those who are comfortable with using CSS only and want a dropdown to appear on hover, you can easily implement it by adding the following code:

.dropdown:hover .dropdown-content {display: block}

You can see this in action on this fiddle: https://jsfiddle.net/8n2xrbhq/1/

If you prefer the dropdown to appear on click instead, please let me know in the comments as it will require some JavaScript.

Answer №2

To simplify this task, jQuery could be used; however, here is an example implemented with vanilla JS. The trick is to utilize a common css class for all dropdown elements.

Check out the code snippet on jsFiddle

//HTML
<body>
 <div class="wrapper">
   <div class="Dropdown">
    <div class="Dropdown__btn">Dropdown 1</div>
     <ul class="Dropdown__list">
       <li>Item A</li>
       <li>Item B</li>
       <li>Item C</li>
     </ul>
   </div>
   <div class="Dropdown">
    <div class="Dropdown__btn">Dropdown 2</div>
     <ul class="Dropdown__list">
       <li>Item A</li>
       <li>Item B</li>
       <li>Item C</li>
     </ul>
   </div>
   <div class="Dropdown">
    <div class="Dropdown__btn">Dropdown 3</div>
     <ul class="Dropdown__list">
       <li>Item A</li>
       <li>Item B</li>
       <li>Item C</li>
     </ul>
   </div>
 </div>
</body>

// CSS
.Dropdown__list {
 display: none
}

.is-opened.Dropdown .Dropdown__list {
 display: block
}

//JS

var dropdowns = document.querySelectorAll('.Dropdown');


var closeAllDropdowns = function() {
 dropdowns.forEach( function(current) {
     current.classList.remove('is-opened')
 })
}
var toggleDropdown = function(e) {
 closeAllDropdowns();
 var dropdown = e.currentTarget.parentElement;
 dropdown.classList.toggle('is-opened')
}
for (i = dropdowns.length - 1; i >= 0; i--) {
 dropdowns[i].querySelector('.Dropdown__btn').addEventListener('click', toggleDropdown)
}

Answer №3

For a different approach, you may want to check out this example on https://jsfiddle.net/aswin_89/hkred6d7/9/

I made some adjustments to your JavaScript code:

/* With this function, when the user clicks on the button,
the dropdown content will toggle between hiding and showing */
function myFunction() {
   event.target.nextElementSibling.classList.toggle("show2");
}

function clearClasses (target){
  document.querySelectorAll('.dropdown-content.show2').forEach((item)=>{
    if(event.target.nextElementSibling !== item)
      item.classList.remove('show2');
  })
}

// To close the dropdown when the user clicks outside of it
window.onclick = function(e) {
  clearClasses(event.target.nextElementSibling);
}

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

Strip the CSS styling from an image (the CSS being included in the generated code)

I need to remove the CSS styling from an image, but I can't modify the generated code where it's coming from. My actual code looks like this: <div class="bubble"> <img id="one" src="/static/webupload/MyronArtifacts/images/descarga.png ...

Tips for exchanging divs in a mobile view using CSS

Illustrated below are three separate images depicting the status of my divs in desktop view, mobile view, and what I am aiming for in mobile view. 1. Current Status of Divs in Desktop View: HTML <div id="wrapper"> <div id="left-nav">rece ...

Tips for relocating anchor elements to less desirable locations

My website has an issue with anchor elements appearing too frequently and not in the desired location. I need someone to help fix this so there are only two anchors displayed. After checking my code, it seems like there are not more than the specified num ...

Encountering limitations in accessing certain object properties with the openweathermap API

As I integrate axios into my react application to retrieve weather data from the openweathermap api, I'm encountering some issues with accessing specific properties from the JSON object returned by the API call. For instance, I can easily access data. ...

What is the best way to extract the innerHTML of every button and exhibit it in a text box?

How can I create a simpler JavaScript code for clicking buttons to input letters into a text box? Instead of creating getElementByID for each button, is it possible to use some kind of loop? <div id="alpha" > <br/> <div align="cente ...

Over time (a few days), the setInterval function causes the react app to become unresponsive

In my React app (Next.js), I have implemented a feature that displays a QR code refreshing every 5 seconds, alongside a clock that updates every second. Additionally, I have integrated a service worker to enable Progressive Web App (PWA) functionality and ...

AngularJS directive for attributes. Steps for adding a second attribute directive during compilation phase

I am interested in creating an attribute directive that adds an icon to a button when it is disabled. Click here to see a similar example on Fiddle In addition, I would like to include the ng-disabled directive during the compile process (with the value ...

What steps can I take to generate 12 random div elements using jQuery out of a pool of 30?

Currently, all the words are displaying, but I would like the script to randomly select 12 out of the 30 words var randomdivs = $("wordstyle").get().sort(function(){ return Math.round(Math.random())-0.5; }).slice(0,12) $(randomdivs).show(); The follo ...

Modify the bootstrap dropdown background to display only an image

I am looking to make the image in a dropdown/dropup menu fill the entire background of the dropdown. Currently, there is still white space visible around the image. How can I ensure that the dropdown shows only the image and includes a scroll wheel? Addit ...

Correcting W3C validation issues is essential

I am encountering errors in my W3C validation process. Even though I have set <!DOCTYPE HTML> for my page, I continue to experience issues as shown in the image below. I have been trying to troubleshoot and resolve these errors without much success ...

Creating a Node.js asynchronous setup function

I'm in the process of transitioning from Nodejs v12 to v14 and I've noticed that v14 no longer waits for the setup function to resolve. My setup involves Nodejs combined with Express. Here's a simplified version of my code: setup().then(cont ...

Click to Resize Window with the Same Dimensions

I have a link on my website that opens a floating window containing more links when clicked. <a href='javascript:void(0);' onclick='window.open("http://mylink.html","ZenPad","width=150, height=900");' target='ZenPad'>&l ...

Closing the Angularstrap dropdown when clicking elsewhere

Is there a method to close an angularstrap dropdown only when clicking outside of it? The current behavior is that it closes when you click inside the dropdown. Thank you ...

Using JQuery to loop through every link in a particular row of a table

Here is the table I am working with: <table border="1" id="tbl"> <tr class="clsHead"> <td> <a href="b.aspx">first row first cell</a> </td> <td> <a href="b.asp ...

Personalize the styling of Material UI Tables - final element customization

I've been attempting to adjust the padding of the Material UI Table. The last-child element is receiving a 24px padding which I'm trying to modify. Despite my attempts at overriding the theme and using classes{{root: classes.xxx}}, I haven't ...

Unable to fulfill all the promises in JavaScript

As I develop a filter feature, I have categories and cities in the format: ['New York'], ['Cars']. The goal is to iterate through them to retrieve products based on each city or category. My approach involves storing these products in t ...

A guide on utilizing the index column for multiple tables using just one statement in the datatable js library

I've incorporated the datatable js for managing two tables on a single page. HTML <!-- Table#1 --> <table class="dataTable"> <thead> <tr> <td>#</td> <td>col1</td> </tr> &l ...

Building secure and responsive routes using next.js middleware

After setting up my routes.ts file to store protected routes, I encountered an issue with dynamic URLs not being properly secured. Even though regular routes like '/profile' were restricted for unauthenticated users, the dynamic routes remained a ...

Is it advisable to refrain from loading images in a jQuery ajax request?

I'm currently developing a Chrome extension that extracts data from webpages successfully. However, I want to enhance its performance by blocking image loading during the parsing process in the background. Is there a way to achieve this? $("#data").l ...

Trouble with Unveiling the Secondary Accordion

I am having issues adding a second accordion next to the existing one. Even though the code is working fine in the tryit editor v3.6 online, it doesn't seem to display correctly for me. I have made sure that I am using the latest versions of all scrip ...