Select Menu (Code Languages:CSS, JS, HTML, BBCode)

I'm currently in the process of setting up a BB code for a forum I moderate.

Here's the code snippet I'm using to generate a dropdown box that users can add to the signature field of their profiles:

<!DOCTYPE html>
<html>
<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">My Characters</button>
  <div id="myDropdown" class="dropdown-content">
    <a>{text}</a>
  </div>
</div>
<head>
<style>
/* Dropdown Button */
.dropbtn {
    border: 1px dotted !important;
  background-color: #1b1b1b;
  border-color:white !important;
  color: white;
min-width: 500px !important;
  font-size: 16px;
  cursor: pointer;
}

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

/* The container <div> - needed to position the dropdown content */
.dropdown {
display: inline-block;
position: relative;
 z-index: 500 !important;
min-width: 500px !important;
}
...

The issue I'm facing is that only the first dropdown box on each page is functioning properly. The rest are unresponsive to clicks. Is there a way to enable multiple dropdowns to work simultaneously without directly mentioning each one in the code?

Answer №1

Make sure each dropdown has a unique ID; IDs cannot be duplicated. Remove the ID and pass the clicked item to the function.

In the function, utilize the clicked item to access the parentNode and locate the container by its class, then toggle visibility using togle():

/* Toggle dropdown content when button is clicked */
function myFunction(item) {
  item.parentNode.querySelector(".dropdown-content").classList.toggle("show");
}

// Close dropdown if click occurs outside of it
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');
      }
    }
  }
}
/* Styles for Dropdown Button */
.dropbtn {
    border: 1px dotted !important;
  background-color: #1b1b1b;
  border-color:white !important;
  color: white;
min-width: 500px !important;
  font-size: 16px;
  cursor: pointer;
}

/* Hover and focus effects for Dropdown button */
.dropbtn:hover, .dropbtn:focus {
  background-color: Black;
}

/* Container for positioning the dropdown content */
.dropdown {
display: inline-block;
position: relative;
 z-index: 500 !important;
min-width: 500px !important;
}

/* Styling for hidden Dropdown Content */
.dropdown-content {
  display: none;
border: 1px solid !important;
    border-color: white !important;
  background-color: rgba(20,20,21,0.95) !important;
  color:#fff;
  min-width: 500px;
    max-height: 250px !important;
  z-index: 500 !important;
    overflow-y: scroll !important;
}
/* Links inside the dropdown */
.dropdown-content a {
  padding: 8px 16px;
  display: block;
}

/* Change link color on hover */
.dropdown-content a:hover {
    }

/* Display dropdown menu using JS with 'show' class */
.show {display:block;}
<div class="dropdown">
  <button onclick="myFunction(this);" class="dropbtn">My Characters</button>
  <div class="dropdown-content">
    <a>{text}</a>
  </div>
</div>

<div class="dropdown">
  <button onclick="myFunction(this);" class="dropbtn">My Other Characters</button>
  <div class="dropdown-content">
    <a>{text}</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

Are several UDP sockets open across various ports?

I'm trying to get the port of a receiving server using the following code snippet: var dgram = require("dgram"); var start = 27015; for(var i = start; i < (start + 100); i++) { var server = dgram.createSocket("udp4"); server.on("message ...

Attach data to a specific position within a jQuery DataTable

Hello everyone! I'm currently attempting to integrate tableInfo into a jquery DataTable, as shown below: However, when I modify the value in show-list, the information shifts down to the center of the column, as illustrated here: I have experimented ...

Exploring the world of MVC4: Enhancing user experience with client-side

Solution: The answer provided by @www.innovacall.com is correct, I initially misunderstood it but now it works perfectly. Thank you for the help. Initial issue: I have been struggling with finding a solution to my problem. In my project, there is a mod ...

html - displaying a new page within the content of the current page

I have a question about basic HTML knowledge that I find embarrassing Is it possible to open or load a second page within my first page? I want a menu button that will load the second page. <li class="current"><a href="first.html" target = "myC ...

Issues with location forecasts and .getPlace() when utilizing the Google Maps loader for Place Autocomplete in Vue are causing functionality problems

After setting up a Vue 2 app using the vue cli, I noticed that when typing an address, no suggestions were populating from the dropdown. Checking the network tab, I observed the AutocompletionService.GetPredictions call triggering without any errors upon p ...

Ways to retrieve the locale parameter from the URL in Next Js

For my Next Js application, I've successfully implemented multi language support using the next-i18next module. Everything is working smoothly. Below is the code for my NabBar component: const NavBar = ({...props}) => { const router = useRouter( ...

Using *ngFor with a condition in Angular 4 to assign different values to ngModel

I am new to Angular 4 and encountering an issue with using *ngFor in conjunction with HTML drop-down select and option elements. My categories array-object looks like this - categories = [ { id:1, title: 'c/c++'}, { id:2, title: 'JavaScri ...

Similar to TypeScript's `hasOwnProperty` counterpart

When working with TypeScript objects, is there a way to loop through a dictionary and set properties of another dictionary similar to how it is done in JavaScript? for (let key in dict) { if (obj.hasOwnProperty(key)) { obj[key] = dict[key]; } } If ...

What methods can I use to gauge the performance of my angular website?

After completing my web project with nodejs and expressjs on the backend and angularjs on the frontend, I am worried about the performance implications. People say that JavaScript can be dangerous if not used correctly, so I ran jshint to verify my synta ...

Tips for adding one document to two separate collections using JavaScript and MongoJS

Having trouble inserting data into two separate tables using javascript and mongojs. While I was able to successfully insert into a single collection by following the npm mongojs documentation, I couldn't find a solution for multiple collections on th ...

Animate in Angular using transform without requiring absolute positioning after the animation is completed

Attempting to incorporate some fancy animations into my project, but running into layout issues when using position: absolute for the animation with transform. export function SlideLeft() { return trigger('slideLeft', [ state('void&a ...

Is it the right time to implement a JavaScript framework?

Is there a need for using JavaScript frameworks like Angular or React if you are not developing single-page websites or components that receive live updates? ...

What is the best way to transfer data entered into a textbox through an onclick Alert event into a database?

UI https://i.stack.imgur.com/c2cqo.png Here is the PHP code I have been struggling with. It is meant to save input data into a database, but I can't seem to get it right: if (isset($_POST['rjctrsn-data']) && !empty($_POST['rjc ...

Manipulating the .innerHTML property allows for selectively replacing sections

In my JavaScript code, I am trying to display a video along with a countdown timer. Once the countdown finishes, it should switch the content of the div to show a question. Below is my current implementation: <script type="text/javascript"> ...

Having trouble posting data in node.js using MongoDB and EJS

Hey everyone, I'm currently working on creating a page with a form and text input fields. However, I'm encountering an error that says "Cannot Post". Here is my code, any help would be greatly appreciated. Why isn't it working? This is app. ...

How to manage a POST request in a GET route using express.js

Exploring the world of Express and Node.js together for the first time has brought me face to face with what appears to be a simple roadblock. I've set up an API route that utilizes the GET method. Here's the route: app.get('/api/v1/all&apo ...

What is the best way to access the dimensions of a parent element in React with Hooks?

I am currently working on a new component and I am facing the challenge of obtaining the width and height of its parent <div>. Since all my components are functional ones using Hooks, the examples I found involving classes do not fit my case. Here i ...

Tips for maintaining video playback in HTML5 when the video element is clicked

I am currently working on creating a straightforward video conference setup and I specifically want to only allow the fullscreen feature when sharing the video element. I also want to disable all other controls such as volume, mute, seek, play, pause, and ...

Flexbox does not seem to be cooperating with CSS Auto Width

Hello Overflowers, I've designed an HTML page with the following specifications: 1. Resetting HTML, BODY, DIVs, and SPANs to have no border, padding, margin, or outline 2. Setting display properties for HTML, BODY, and DIV elements 3. Defining hei ...

Why do I keep receiving the error message "Cannot set property of undefined"?

In the midst of a small project that involves utilizing nuxt, js, and axios, I encountered an issue when attempting to assign the response data to my formFields object. Despite having declared formFields within the data section, I kept receiving an error m ...