I want to have multiple dropdown buttons, but I'm not sure how to optimize my javascript so that it can include multiple IDs that can trigger more than one dropdown while also the arrow to the right of it rotates as the dropdown menu is triggered. Not sure how to get the second button to trigger? I have a sample below:
const dropdownBtn = document.getElementById("dropdown-btn");
const dropdownMenu = document.getElementById("a");
const toggleArrow = document.getElementById("dropdown-arrow");
// Toggle dropdown function
const toggleDropdown = function () {
dropdownMenu.classList.toggle("dropdown-show");
toggleArrow.classList.toggle("dropdown-arrow");
};
// Toggle dropdown open/close when dropdown button is clicked
dropdownBtn.addEventListener("click", function (e) {
e.stopPropagation();
toggleDropdown();
});
// Close dropdown when dom element is clicked
document.documentElement.addEventListener("click", function () {
if (dropdownMenu.classList.contains("dropdown-show")) {
toggleDropdown();
}
});
.dropdown-list {
visibility: hidden;
opacity: 0;
transform: translateY(0.5rem);
transition: all 0.1s cubic-bezier(0.16, 1, 0.5, 1);
}
.dropdown-list a {
display: flex;
align-items: center;
column-gap: var(--gap);
padding: 0.8rem 1rem;
text-decoration: none;
color: black;
}
.dropdown-list a:hover {
background-color: #e8e8e8;
}
.dropdown-show {
visibility: visible;
opacity: 1;
transform: translateY(0rem);
}
.dropdown-arrow {
transform: rotate(180deg);
transition: 0.2s ease;
font-weight: bold;
}
<link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet" />
<button class="dropdown-btn" id="dropdown-btn">
LISTEN NOW
<i class='bx bxs-chevron-up' id="dropdown-arrow"></i>
</button>
<div class="dropdown-list" id="a">
<a href="#">
Apple
</a>
<a href="#">
Spotify
</a>
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<button class="dropdown-btn" id="dropdown-btn-b">
LISTEN NOW
<i class='bx bxs-chevron-up' id="dropdown-arrow-b"></i>
</button>
<div class="dropdown-list" id="b">
<a href="#">
Apple
</a>
<a href="#">
Spotify
</a>
</div>