Harry Harry - 4 months ago 8
Javascript Question

Is it possible to create one javascript that controls multiple dropdown menus?

I have created a very simple javascript:

function dropdownFunction() {
document.getElementById("dropdown").classList.toggle("show");
}


With the following HTML:

<div class="dropdown">
<button onclick="dropdownFunction()" class="dropbtn">Dropdown</button>
<div id="dropdown" class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>


This works, however as you would expect when I used the same HTML code to create a second dropdown button, when clicked it opens the first buttons dropdown menu. I was wondering whether or not it would be possible to modify that script so that I can use that function for all dropdowns, as oppose to having to create new functions for every dropdown button I use on the website.

Answer

Sure. When you call the function pass a reference to the element that was clicked:

onclick="dropdownFunction.call(this)"

...and then in the function use that reference to find the appropriate div:

this.parentNode.querySelector(".dropdown-content").classList.toggle("show");

Here's a working demo of the above in context:

function dropdownFunction() {
  this.parentNode.querySelector(".dropdown-content").classList.toggle("show");
}
.dropdown-content {
  display: none;
}
.show {
  display: block;
}
<div class="dropdown">
  <button onclick="dropdownFunction.call(this)" class="dropbtn">Dropdown</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="dropdownFunction.call(this)" class="dropbtn">Dropdown 2</button>
  <div class="dropdown-content">
    <a href="#">Link A</a>
    <a href="#">Link B</a>
    <a href="#">Link C</a>
  </div>
</div>

Comments