JSFiddle - React, Tailwind, and code Playground

by Alejandro M

HTML

<!DOCTYPE html>
<html>

  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>

  <body>
    <h2>JS Dropdown</h2>
    <p>Click on the button to open the dropdown menu.</p>

    <div class="dropdown">
      <button class="dropbtn">Dropdown</button>
      <div class="dropdown-content">
        <a href="#home">Home</a>
        <a href="#about">About</a>
        <a href="#contact">Contact</a>
      </div>
    </div>

    <div class="dropdown">
      <button class="dropbtn">Dropdown</button>
      <div class="dropdown-content">
        <a href="#home">Home</a>
        <a href="#about">About</a>
        <a href="#contact">Contact</a>
      </div>
    </div>

    <div class="dropdown">
      <button class="dropbtn">Dropdown</button>
      <div class="dropdown-content">
        <a href="#home">Home</a>
        <a href="#about">About</a>
        <a href="#contact">Contact</a>
      </div>
    </div>
  </body>

</html>

SCSS

.dropdown {
  position: relative;
  display: inline-block;
  
  .dropbtn {
    background-color: #3498DB;
    color: white;
    padding: 16px;
    font-size: 16px;
    border: none;
    cursor: pointer;
    &:hover, &:focus {
      background-color: #2980B9;
    }
  }
  
  .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    &.show {
      display: block;
    }
    a {
      color: black;
      padding: 12px 16px;
      text-decoration: none;
      display: block;
    }
  }
}

JavaScript

// btn event delegation
document.body.addEventListener("click", function onClick(event) {
  if (event.target.matches('.dropbtn')){
  	// reset all visible dropdowns 
    var dropdowns = document.getElementsByClassName("dropdown-content");
    for (let i = 0; i < dropdowns.length; i++) {
    	// but not the active
      if(event.target.closest(".dropdown") != dropdowns[i].closest(".dropdown")){
      	if (dropdowns[i].classList.contains('show')) {
        dropdowns[i].classList.remove('show');
      }
      }
    }

    const wrapper = event.target.closest(".dropdown");
    const dropdown = wrapper?.querySelector(".dropdown-content");
    dropdown?.classList.toggle("show");
    }
});

// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
  if (!event.target.matches('.dropbtn')) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    for (let i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}