Displaying various dropdown content when different buttons are clicked

In my interface, I have implemented a drop-down menu that consists of two options. When the "Add Equipment" option is clicked, everything functions properly as expected. However, when I select the "Deployed Equipments" option, the drop-down for "Add Equipment" unexpectedly appears.

This is what occurs when I click on "Deployed Equipments":

There seems to be an issue with how the dropdown menus are interacting. Do you see any errors in my implementation?

Below is the CSS code being used:

/* CSS code for dropdown button */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}

/* Hover and focus styling for dropdown button*/
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}

/* Container for dropdown content */
.dropdown {
position: relative;
display: inline-block;
}

/* Styling for dropdown content (initially hidden) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}

/* Links inside dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}

/* Change color of links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}

/* Display dropdown menu when active */
.show {display:block;}

Here's the HTML code:

<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Add Equipment</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>

<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Deployed Equipments</button>
<div id="myDropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>

And finally, here's the JavaScript code:

<script>

function myFunction() {
    document.getElementById("myDropdown").classList.toggle("show");
}

// Close dropdown menu if user clicks outside
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {

    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

</script>

Answer №1

Two divs share the same id myDropdown. To access the dropdown without using ids for the div, you can utilize the code below which utilizes nextElementSibling of the clicked button. I hope this solution is helpful.

function myFunction() {
    //Remove the 'show' class for all dropdowns except the current one
    [].slice.call(document.getElementsByClassName("dropdown-content")).map(function(el){
         if (this.event.target.nextElementSibling !== el)
            el.classList.remove("show");
    });

    //The 'this.event.target' refers to the clicked button. Retrieve the next element and toggle the 'show' class.
    this.event.target.nextElementSibling.classList.toggle("show");
}

Example:

function myFunction() {
[].slice.call(document.getElementsByClassName("dropdown-content")).map(function(el){
if (this.event.target.nextElementSibling !== el)
el.classList.remove("show");
});

this.event.target.nextElementSibling.classList.toggle("show");
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function (event) {
if (!event.target.matches('.dropbtn')) {
[].slice.call(document.getElementsByClassName("dropdown-content")).map(function(el){
el.classList.remove("show");
});
}
}
/* Dropdown Button */

.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
/* Dropdown button on hover & focus */

.dropbtn:hover,
.dropbtn:focus {
background-color: #3e8e41;
}
/* The container <div> - needed to position the dropdown content */

.dropdown {
position: relative;
display: inline-block;
}
/* Dropdown Content (Hidden by Default) */

.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
}
/* Links inside the dropdown */

.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
/* Change color of dropdown links on hover */

.dropdown-content a:hover {
background-color: #f1f1f1
}
/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */

.show {
display: block;
}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Add Equipment</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>

<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Deployed Equipments</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>

Answer №2

Avoid assigning identical IDs to multiple elements within the same webpage. It seems that both elements have been labeled as myDropdown.

Answer №3

Check out this jQuery solution:

$('.dropdown').click(function() {
$(this).find(".dropdown-content").toggleClass("show");
});
/* Dropdown Button */
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}

/* Dropdown button on hover & focus */
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}

/* The container <div> - needed to position the dropdown content */
.dropdown {
position: relative;
display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}

/* Change color of dropdown links on hover */
.dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
.show {display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<button class="dropbtn">Add Equipment</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>

<div class="dropdown">
<button class="dropbtn">Deployed Equipments</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</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

Having trouble rendering components due to conflicts between React Router and Semantic UI React

Below is the code in my App.js: import { useRecoilValue } from 'recoil'; import { authState } from './atoms/authAtom'; import { ToastContainer } from 'react-toastify'; import { ProtectedRoute } from './layout/ProtectedRou ...

How to properly align labels with input fields using CSS

I'm facing a design challenge with my form, showcased in this fiddle: https://jsfiddle.net/ejkvp88v/2/. The inputs are centered, which is great, but I'm struggling to align the labels above the inputs on the left side. I've searched through ...

Creating a fixed sidebar on the left and right using Bootstrap 5

Is it possible to create a left and right fixed sidebar with content in the middle using two <nav> elements in Bootstrap 5 markup structure? Here's an example of what I mean: <nav> <div>left sidebar</div> </nav> <mai ...

How can I resolve the issue of not returning anything ondrop in my code?

Whenever I drop my div containing an image, I don't see anything. And when I try to access its ID, I get a null value. How can I extract information from a div with an image and append a row with it? For code samples or to check the codepen example, v ...

Tips for customizing the appearance of path elements within an external SVG file being utilized as a background image

How can I change the color of the paths in an SVG background image assigned to a div using CSS? ...

Tips for preventing a figcaption from shifting the image position

I'm trying to add a figcaption to an image without moving the image from its original position due to the figcaption. Below is the CSS code I'm using for the figcaption. Here is the code for an image with a figcaption. figcaption { text-alig ...

Utilizing numerous copies of a single plugin

I recently integrated a plugin called flip-carousel.js into my website and here is an example of how it looks on the site. Check out the sample implementation Now, I encountered an issue when trying to use multiple instances of the same plugin. When init ...

JavaScript drop-down menu malfunctioning

I am currently in the process of learning web development languages, and I'm attempting to create a dropdown list using JavaScript (I previously tried in CSS without success). I would greatly appreciate it if you could review my code and let me know ...

Learn how to use onclick event in an anchor tag to send post values through Ajax!

Can I send post values via AJAX using an onclick event on an anchor tag? I've tried the following code but I'm not receiving any post values. How can I make it work? ............................................................................. ...

How to set DIVS to be hidden when the page first loads

I am currently working on a project where I need to use JavaScript to hide certain <div> elements when the page loads. I have also included jQuery in my code. Below is what I have tried so far: $(document).ready(function() { hide(); function hid ...

Error encountered in my JavaScript file - Unexpected Token < found on line 1 of the loadash.js script

I am right at the end of creating a sample dashboard with charts using dc.js, but I have hit a roadblock with one error remaining. This error is causing an issue. Unexpected token < on line 1 for loadash.js. The loadash.js file is valid, but for som ...

How can line-height be used to crop the bottom of characters in CSS?

My goal is to make a text character reach the edge below it. Despite having no margin or padding, a space still exists due to the inherent spacing below the font characters. Lowering the line-height removes the top of the characters, but I want to chop o ...

How can I incorporate a background image into an Angular template without using a CSS file?

Can you please provide guidance on setting a background image in Angular using the ngFor directive within a carousel grid layout? <div class="slide slick-bg s-bg-1" *ngFor="let movie of nowPlaying" style="https://image.tmdb.org/ ...

Spread out the items within an inline block

Is there a way to create space between icons that are in an inline block without them touching each other? One solution could be to add a container around each icon, center the icons within the containers, and then place the containers in the block. You c ...

Jquery solution for toggling multiple Divs individually

I'm currently working on a small application that has both a sidebar menu and a header menu. My goal is to have all items in these menus toggle the visibility of content in one main window or page. When a button is clicked, I want it to show the corre ...

Having trouble with sending a post request through ajax

Whenever I try to initiate an Ajax request upon clicking a button, the request never seems to get executed. Below is the snippet of my HTML code : <!DOCTYPE html> <html lang="en"> <head> <title>User Form</title> ...

Maintain the background div while scrolling horizontally

I am facing an issue with my wide bar chart where I use iScroll to enable horizontal scrolling. Behind the bar chart, there are horizontal lines that should move along in the background as the user scrolls horizontally. The challenge is to keep the lines v ...

Unable to navigate to different tabs within the html tab content section

When I navigate to my new profile tab, I encounter an issue where I cannot switch to other tabs by clicking on them. Below is the code snippet that I am using. Navigating from the Dashboard tab to the New Profile tab works fine, but the reverse direction d ...

Is there a way to determine if a browser is operating in compatibility mode?

Is there a way to determine if the browser is in compatibility mode or not? I need to apply different CSS depending on the mode. ...

Obtained a ZIP file via CodeSandbox that contains a Vue.JS webpage. However, the index.html file yielded an

I have created my first ever Vue.JS / Vue2Leaflet app. It runs perfectly fine on codesandbox.io. However, when I download the ZIP file and try to open the index.html file, it appears blank. Is there something specific that needs to be done to make it work, ...