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

Does Google Cloud CDN not store data from the storage bucket?

I've been experimenting with combining a Load Balancer, Cloud Storage, and CDN for the past few weeks. Unfortunately, I have not been successful in getting it to work as expected. I uploaded some static files (2 jpgs, svgs, and css files) to a multi- ...

What is the reason behind Express serving the static file through the router, while also causing the path to the scripts folder to

Directory Layout app ├── app.js ├── public │   ├── data │   │   └── data.json │   ├── index.html │   └── js │   ├── filter-list.js └── routes └── index.js Setting up ap ...

Guide on automatically inserting a colon (:) after every pair of characters in Angular

I am looking to automatically insert a colon (:) after every 2 characters in my input field: HTML <input nz-input type="text" appLimitInput="textAndNumbers" name="mac" formControlName="mac" (keydown.space)=&qu ...

Utilizing Material-UI components for a seamless navigation button experience

After reviewing the example on https://material-ui.com/guides/composition/#button, I have implemented a button in my main page: <BrowserRouter> <Box m={2}> <Button size="large" variant="cont ...

Inconsistent CSS3 transitions behavior in Firefox 4

I have been playing around with some css3 transitions and created a slider test. It works perfectly in webkit browsers, but I have noticed an issue in Firefox 4. When clicking on the left link for the first time, the slider is supposed to slide to the left ...

The JavaScript animations in AngularJS using ng-class are not being activated

I've been attempting to apply js-defined animations to the ng-class directive using the standard syntax of add and remove, but for some reason, the animations are not running. After checking the logs, it seems that the add and remove functions are not ...

In React + TypeScript, learn how to effectively pass down a function from a container component to a

I am currently working on developing a tabs application using React and Typescript. The main component, Tabs, manages the state and passes it down to the Content component. Additionally, I have implemented a function called 'handleName' which is ...

"Unusual HTML and jQuery quirk causing a perplexing issue: a function that keeps looping inexp

A unique code written in javascript using jQuery allows users to create a "box" on a website with each click of a button, triggering an alert message upon clicking the box. The process is as follows: 1) Clicking the "Add (#addBox)" button appends a new li ...

What is the method to retrieve the information from a JSON response of a POST request in a Next/React application?

I am currently leveraging the Next.js API route to manage a POST request and subsequently send a response back to the frontend. To verify this process, I have utilized the Rapid API client extension and confirmed that a response is indeed being sent to the ...

The browser automatically adds a backslash escape character to a JavaScript object

When attempting to send an MQTT message to a topic from my angular app, the message needs to be in a specific syntax: { "Message": "hello" //the space after : is mandatory } However, upon sending the message in the correct format, the browser aut ...

Making JSON function in Internet Explorer

I'm encountering an issue retrieving data from a JSON feed specifically in Internet Explorer. Here's the problem. It functions correctly in Firefox, Chrome, and Safari, but fails to alert in IE: function perform_action(data){ alert(data); } ...

Disable text input in Flatpickr and remove the default iPhone calendar

We are facing an issue with the iPhone and iPad when using flatpickr for our calendars. When the calendar is opened, the cursor automatically focuses on the text box, triggering the default iPhone calendar to appear below. This problem does not occur on An ...

What are some ways to design unique custom data grid toolbar elements?

I am having trouble syncing my custom toolbar buttons with the imported material data grid toolbar components. I would like them to match in style, specifically applying the material styles to my custom components. However, I have not been able to find a w ...

How does Jasmine compare to the second parameter with the toBeCloseTo function?

Jasmine's documentation is often brief, but not always sufficient. I am curious about the second parameter of the toBeCloseTo function. The official reference only provides this example: it("The 'toBeCloseTo' matcher is for precision mat ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

What could be causing the issue with the 100% height and 100% width not functioning properly on my ASPX page?

The CSS and HTML code work perfectly in an isolated test environment: body, html { height: 100%; min-height:600px; min-width:800px; overflow:hidden; margin:0;padding:0; } html {overflow:auto;} .fill {height:100%; width:100%; backgro ...

Tips for effectively handling unique properties of a React component (such as Redux integration and custom CSS) when sharing through NPM distribution

Question: How can custom Redux containers and CSS be effectively managed with NPM? It can be challenging to handle these custom files through traditional package distribution platforms like NPM, especially when they need to be edited in various projects. ...

Selected value is not displayed in the textbox when using autocomplete feature

---Ajax---- An issue has arisen with the autocomplete feature. While typing "wi" (for example, wipro), the drop-down list appears as expected. However, if only "wi" is selected in the text box, $(document).ready(function () { $("#company_name").key ...

Reposition HTML content using regular expressions

My objective is to locate a block of HTML that contains comments and relocate it after the header section. The comment itself remains constant, but the content within the block varies across different pages and needs to be replaced using Dreamweaver' ...

Puppeteer is unable to detect the node.js handlebars helpers

I'm utilizing puppeteer in NodeJs to generate a PDF file. I use handlebars to render the template and pass variables during compilation for handlebars to access them. Here is the current code snippet: const browser = await puppeteer.launch({ he ...