Creating a Dropdown Menu: Connecting Multiple Buttons to a JavaScript Function

I am currently working on creating a dropdown menu. I have already written the HTML and Javascript for two buttons, but I'm not sure how to connect the second button to the Javascript function. Do I need to write another function()?

<div class="dropmenu">
  <button onclick="myFunction()" class="button1" style="background-color:#61117F ;">Dropdown</button>
  <div id="Dropdown1" class="dropmenu-content">
    <a href=" http://www.apple.com/">Apple</a>
    <a href="https://www.google.com/">google</a>
  </div>
</div>

<div class="dropmenu">
  <button onclick="myFunction()" class="button1" style="background-color:#d7791b ;">DropDown2</button>
  <div id="Dropdown2" class="dropmenu-content">
    <a href=" https://www.yahoo.com/">Yahoo</a>
    <a href="https://www.facebook.com/">FB</a>
  </div>
</div>

<script>
  function myFunction() {
      document.getElementById("Dropdown1").classList.toggle("show");
      window.onclick = function(event) {
          if (!event.target.matches('.button1')) {
            var drop = document.getElementsByClassName("dropmenu-content");
            var i;
            for (i = 0; i < drop.length; i++) {
              var Dropdown = drop[i];
              if (Dropdown.classList.contains('show')) {
                Dropdown.classList.remove('show');
              }
            }}}
</script>

Answer №1

To activate a specific dropdown menu, assign a data-attribute to your button containing the ID of the dropdown you wish to affect. You can also apply a CSS class like "trigger-event" to trigger the event.

<button data-dropdown="Dropdown1" class="trigger-event" style="...">
...
<button data-dropdown="Dropdown2" class="trigger-event" style="...">

Then, utilize the data attribute to target the correct dropdown:

$(document).on('click', '.trigger-event', function(){
    var dropdownId = $(this).data("dropdown");//or attr("data-dropdown")
    myFunction(dropdownId);
});

function myFunction(dropdownId) {
    document.getElementById(dropdownId).classList.toggle("show");
    window.onclick = function(event) {
    ...
    }
}

Answer №2

If you want to streamline your JavaScript code, simply pass the clicked button to the function and locate its sibling with the class dropmenu-content. Then, toggle the show class for that element.

window.myFunction = function(e) {
  var dropdown = e.parentNode.getElementsByClassName('dropmenu-content')[0];
  dropdown.classList.toggle('show');
}
.dropmenu-content {
  display: none;
}

.dropmenu-content.show {
  display: block;
}
<div class="dropmenu">
<button onclick="myFunction(this);" class="button1" style="background-color:#61117F ;">Dropdown</button>
  <div id="Dropdown1" class="dropmenu-content">
 <a href=" http://www.apple.com/">Apple</a>
<a href="https://www.google.com/">google</a>
  </div>
</div>

<div class="dropmenu">
<button onclick="myFunction(this);" class="button1" style="background-color:#d7791b ;">DropDown2</button>
  <div id="Dropdown2" class="dropmenu-content">
    <a href=" https://www.yahoo.com/">Yahoo</a>
<a href="https://www.facebook.com/">FB</a>
  </div>
</div>

Answer №3

function toggleDisplay(dr){
var element = document.getElementById(dr);
var display = element.style.display == "block" ? "none" : "block";
element.style.display = display;
}  
.button1{
border:none;
border-radius:5px;
padding:10px;
color:white;
margin:5px;
}
.dropmenu-content{
margin:10px;
}
.dropmenu-content a{
text-decoration:none;
color:brown;
box-shadow:1px 1px #ccc;
padding:5px;
border-left:solid 3px green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropmenu">
  <button onclick="toggleDisplay('Dropdown1')" class="button1" style="background-color:#61117F ;">Dropdown1 &#x25BC;</button>
  <div id="Dropdown1" style='display:none;' class="dropmenu-content">
    <a href=" http://www.apple.com/">Apple</a>
    <a href="https://www.google.com/">google</a>
  </div>
</div>

<div class="dropmenu">
  <button onclick="toggleDisplay('Dropdown2')" class="button1" style="background-color:#d7791b ;">DropDown2 &#x25BC;</button>
  <div id="Dropdown2" style='display:none;' class="dropmenu-content">
    <a href=" https://www.yahoo.com/">Yahoo</a>
    <a href="https://www.facebook.com/">FB</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

Assistance with jQuery in Javascript is needed

Currently, I am in search of an effective vertical text scroller. My desired scroller would move vertically in a continuous manner, ensuring there is never any empty space while waiting for the next text to appear. I am open to using either JavaScript or ...

Json path that begins with 0

I am encountering a situation where I need to extract data from an API using an https.get request. The issue arises when the json path starts with a 0. Can anyone explain what this means and how can I access the data successfully? https.get(url, function( ...

What is preventing me from using javascript setInterval with a function in a separate external file?

Everything is running smoothly with this code snippet...an alert pops up every 10 seconds <script type='text/javascript'> function letsTest(){ alert("it works"); } var uptimeId = window.setInterval(letsTest, 10000); < ...

What could be causing certain grid items to display in a disorderly manner?

Currently, I am working on a CSS grid layout that resembles the one showcased in this demo. The challenge I'm facing is related to the ordering of items within the grid. Specifically, every 6th and 7th item seem to be out of order and I would like the ...

Troubleshooting problem with Joomla YJK2Slider effects

I recently purchased a Joomla! extension from YouJoomla, but their support forum has been less than helpful. That's why I'm reaching out to you guys for assistance. The main issue I'm encountering seems to be related to an Fx problem or pot ...

When the text is long, it does not extend all the way to the right

I am working on designing a login page and have created an input text field for the user's email address. However, I have noticed that when the email address is long, there is some space left at the end of the border (I suspect it may be due to paddin ...

Identifying input fields using XPath depending on their associated labels

I'm trying to figure out why an XPath query I found returns multiple results when selecting an input based on its label. The first XPath query I used, //input[@id=(//label[.='Max Driving Time_h']/@for)], retrieves 3 inputs even though only o ...

Create seamless communication between Angular application and React build

I am currently engaged in a project that involves integrating a React widget into an Angular application. The component I'm working on functions as a chatbot. Here is the App.tsx file (written in TypeScript) which serves as the entry point for the Rea ...

What is the best way to collapse additional submenus and perform a search within a menu?

Whenever a sub-menu is activated, only the current sub-menu should be open while the others remain closed. I need the search function to be enabled on the text box and display all items containing the specified value while also changing the color of <a ...

``A problem with styles not displaying in the React draft WYSIWYG editor within a Next

Here is an example of the HTML structure: <p><span style="color: rgb(250,197,28);font-size: 96px;">Hello</span><span style="font-size: 96px;"> </span><span style="color: rgb(251,160,38);font-size: 9 ...

What is the best way to set up multiple unique uglify tasks in grunt?

I am facing issues when trying to create multiple Uglify tasks in Grunt. Currently, I have to toggle between commenting and uncommenting a task to get it to work properly. I need assistance in generating two separate minified .js files using this plugin ...

What is the process of turning a picture from a menu file into a clickable link?

I have created a menu with some images included, and I want them to be clickable links. However, currently only the text on top of the images acts as a link when hovered over. I would like the entire image to be clickable, not just the text. I believe I ...

Operating on an angular table arr with the splicing of an object attribute

Encountering an issue. I have a component with some logic for creating and deleting input fields .ts export class AppComponent implements OnInit { resource: Resource[] = []; fieldId = 0; testArr = ['1', '2', '3', ' ...

When I open my website in the browser, the bootstrap card-deck design is not being displayed correctly

I encountered a strange issue while designing my website. The code I wrote for the Bootstrap card-deck class in codeply.com was working perfectly fine. However, when I copied the same code into my PyCharm code editor and then pasted the file link into my b ...

Link a PHP variable to a JavaScript variable

Is there a way to set the value of a JavaScript variable using a PHP variable? $(function(){ $("select[name=myselectlist]").change(function(){ var id = $(this).val(); if(id != 0) { $.post("ajax.php", {"id":id}, func ...

Unable to retrieve data from mysql using javascript and ajax

I am having trouble retrieving data from a MySQL database using AJAX. I have tried adapting my old AJAX code that worked fine in another project, but it doesn't seem to be working here. Here is the JavaScript function I am using: var text1 = documen ...

What strategies can I use to ensure consistent website layout across various zoom levels and browsers?

As a newcomer to web design, I am excited that my site is almost ready to go live. However, I have encountered some significant issues right before launch. When the site is zoomed in or out, the content becomes misaligned at certain zoom percentages. Add ...

Issues with AJAX requests using $.ajax are causing problems

I'm currently facing an issue with my $.ajax function. In a previous function, I have an array called volunteerDist which is then passed to the myAjax(volunteerDis); function. However, every time the program is executed, it triggers the error and comp ...

prevent unauthorized changes to input using browser developer tools in Angular

We have a login page for our application with three fields: "user name," "password," and a "login" button. Here's the issue I'm facing: I enter a valid user name. Then, I open the Browser Developer Tools and input the following code: d ...

In Safari, the scrollbar appears on top of any overlays, popups, and modals

On my webpage, I have a div with the CSS property overflow-y: scroll. The page also features several popup modals and overlays. Strangely, the scrollbar of the div appears on top of these overlays instead of behind them. I attempted to resolve this issue b ...