Numerous CSS/JS Dropdown Menus

I am seeking the ability to implement a dropdown through CSS in various locations within my HTML prototype. This implies that I require the capability to position multiple dropdowns anywhere on the page.

Currently, I utilize this method to generate a single dropdown:

<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Click here 01 </button>
    <div id="myDropdown" class="dropdown-content">
       <a href="#">link</a>
       <a href="#">link</a>
       <a href="#">link</a>
    </div>
</div> 

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

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');
  }
}

} }

How can I create multiple dropdowns using the same JavaScript?

Here is an example that showcases the issue: https://codepen.io/db13/pen/pLGRwr

Answer №1

Using Pure CSS

This method utilizes pure CSS without any JavaScript

#example {
  margin: 30px 0 50px 0;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
}

#example .wrapper {
  display: inline-block;
  width: 180px;
  margin: 0 10px 0 0;
  height: 20px;
  position: relative;
}
...
<div id="example">
  <div class="wrapper">
    <div class="content">
      <ul>
        <a href="#">
          <li>Parent 1 Element 1</li>
        </a>
        ...
      </ul>
    </div>
    <div class="parent">Button 1</div>
  </div>

  <div class="wrapper">
    <div class="content">
      <ul>
        <a href="#">
          <li>Parent 2 Element 1</li>
        </a>
        ...
      </ul>
    </div>
    <div class="parent">Button 2</div>
  </div>

Using Vanilla JavaScript

Implementing functionality with vanilla JavaScript

Find the full code on GitHub here

function fadeIn(el) {
  // Function to fade in an element
  // Code here
}

function fadeOut(el) {
  // Function to fade out an element
  // Code here
}

// More code here...

document.addEventListener("click", function() {
  // Event listener for document click
  // Code here
});
.btn {
  // Button styling
  // CSS rules here
}

.dropdown {
  // Dropdown styling
  // CSS rules here
}
<div>
  <div class="dropdown">
    <button class="btn">First Color</button>
    <ul class="btn-dropdown">
      <li>Brown</li>
      ...
    </ul>
  </div>
  
  // More dropdown elements here
</div>

Using jQuery

This method requires jQuery and an additional plugin

For more details, refer to this Stack Overflow question Drop down list items still clickable when the opacity is zero

$(".btn").on('click', function(e) {
  // Click event for buttons
  // jQuery code here
});

$(document).on('click', function(e) {
  // Document click event
  // jQuery code here
});
.btn {
  // Button styling
  // CSS rules here
}

.dropdown {
  // Dropdown styling
  // CSS rules here
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
  <button class="btn first">Select something</button>
  <ul class="btn-dropdown">
    <li>First</li>
    ...
  </ul>
</div>

// Additional dropdown elements here

Answer №2

One issue you're facing is the importance of making sure that ID's are indeed unique. Your current function is repeatedly targeting the same #myDropdown element.

To address this, consider updating your function to pass in this as the context target and dynamically selecting the dropdown based on its class name.

Take a look at this illustrative example: CodePen Demo

Revise your onclick event like so:

 <button onclick="myFunction(this)" class="dropbtn">Click here 01 </button>

Now, update your myFunction as follows:

var myFunction = function(target) {
   target.parentNode.querySelector('.dropdown-content').classList.toggle("show");
}

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

Utilizing the calc() function to determine height dimensions

I created a very simple layout with 5 divs, which can be viewed here: http://jsfiddle.net/8tSk6/. In this layout, I want the div with the ID "kubka" to have a height of 100% - 100px (height: calc(100% - 100px);). However, I am running into issues as it i ...

The signal property 'ɵunwrapWritableSignal' is not found on the specified type 'typeof import/node_modules/@angular/core/index")'

Despite attempting the solutions provided in previous threads, none of them have been successful for me. Can someone please lend a hand with this issue? https://i.stack.imgur.com/sGRsn.png ...

Are there any better methods for transforming a class component into a hook component?

After some attempts, I'm working on getting this code to function properly using useState: https://codesandbox.io/s/rdg-cell-editing-forked-nc7wy?file=/src/index.js:0-1146 Despite my efforts, I encountered an error message that reads as follows: × ...

Using Telegram markdown: Can you combine both bold *and* italic? (September 2018)

After referencing the Markdown Syntax guide on Telegram’s Wiki page, it appears to be quite straightforward to format text as bold and italic. The guide explains that: *this is in italic* and _so is this_ **this is in bold** and __so is this__ ***this ...

What is the best way to transform a current callback API into promises?

Exploring the transition to working with promises poses a challenge when dealing with callback APIs structured as follows: ###1. Handling DOM load or other one-time event: window.onload; // set to callback ... window.onload = function() { }; ###2. Utili ...

Utilize the fetch function within the useEffect hook to generate a new

How can I effectively implement a component using useEffect? useEffect(() => { fetch('https://website') .then((res) => res.json()) .then((data) => { setData(data) // Utilize fetched data t ...

"Track the progress of a form submission with a loading indicator using Sweet

I am looking to incorporate a waiting time animation when submitting a form, and I prefer using SweetAlert over a traditional loading image. Here is the basic code snippet: $("form").submit(function (e) { e.preventDefault(); // prevents def ...

"Encountering a connectivity problem with Apollo server's GraphQL

I am facing a networking issue or possibly a bug in GraphQL(Apollo-Server-Express). I have tried various solutions but to no avail. When sending a query, everything seems perfect - values checked and request showing correct content with a 200 status code. ...

ERROR: Expo TaskManager Notifications [TypeError: Attempting to call an undefined function (near '...Notifications.presentLocalNotificationAsync...')]

I'm currently trying to figure out how to send notifications whenever a task is triggered, but I keep encountering an error that I can't seem to fix. Here's the error message: TaskManager: Task "background-fetch" failed:, [TypeError: unde ...

Challenges with navbar and CSS alignment in Internet Explorer

Looking for some assistance with a HTML/CSS issue... I've created a new menu using the following CSS and code, but I'm encountering a problem with extra space between lines of text within the menu (specifically with the 'big' and &apos ...

Blazor: Personalizing color variables in _root.scss - A Step-by-Step Guide

Upon inspecting the generated project, I noticed a multitude of color variables such as --bs-body-bg. The developer tools indicate it is in _root.scss, however, that file appears to be non-existent and I suspect those variables may actually reside within b ...

Ways to prevent a div from loading an HTML page

When an external button is clicked, the remove() function on id main is triggered. The issue arises when a user quickly clicks on btn1 and then presses the external button, causing the removal to occur before the event handler for btn1. This results in the ...

How to Pass and Execute Asynchronous Callbacks as Props in React Components

I'm curious about the correct syntax for passing and executing async calls within React components. Specifically: Many times, I'll have a function that looks like this: const doAsync = async (obj) => { await doSomethingAsync(obj) } ...and ...

Angular's Validator directive offers powerful validation capabilities for reactive forms

Referenced from: This is the approach I have experimented with: custom-validator.directive.ts import { Directive } from '@angular/core'; import { AbstractControl, FormControl, ValidationErrors } from '@angular/forms'; @Directive({ ...

How to utilize the ternary operator efficiently to evaluate multiple conditions in React

Is there a way to change the style based on the route using react router? I want the description route to display in orange when the user is in the description route, white when in the teacher-add-course route, and green for all other routes. However, th ...

What is the best way to implement JQuery in order to trigger an event in a text box whenever the user hits the "enter

Also, refrain from submitting the form if the user hits enter in THAT PARTICULAR input field. ...

Uncovering the jsPlumb link between a pair of identifiers

Could someone help me understand how to disconnect two HTML elements that are connected? I have the IDs of both elements, but I'm not sure how to locate their connection in the jsPlumb instance. Any tips on finding the connection between two IDs? ...

What causes an undefined outcome when a promise is fulfilled?

Could you help me understand something? const promise1 = new Promise((resolve, reject) => { setTimeout(() => { if(true) { resolve('success') } else { reject('failure') } }, 4000) }) promise1.then(resul ...

What is the best way to ensure my image adjusts its width and height responsively?

How can I make my image responsive to the size of the container, adjusting not just the width but also the height to fit in a container with a max-width of 1300px? I have created a test image with dimensions of 400px height and 1300px width. Take a look a ...

Having trouble uploading big files on your Windows system?

My challenge is to successfully upload a large file using Angular. Specifically, I am attempting to upload a Human Genome tar file, which is a minimum of 2.5gb in size. Strangely, when I try to upload the file from Linux using any browser such as Chrome or ...