1

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.

1
  • Can you add more dropdown that you mention Commented Jul 10, 2016 at 13:21

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

You have duplicate #dropdown in document.
@Mohammad - the IDs aren't needed, so I'll remove them from the demo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.