Spires
Spires

Reputation: 21

How can I select an item of a dropdown menu?

I created this dropdown and I need to be able select it with javascript so I can compare the Genre to the genres listed in SpotifysAPI. I'm not really sure how to start.. would I be able to give the li's ID's and compare them that way?

HTML:

<div class="dropdown">
 <button class="dropbtn">Select a Genre!</button>
  <ul>
   <li><a href="#">Metal</a></li>
   <li><a href="#">Rock</a></li>
   <li><a href="#">Rap</a></li>
  </ul>
 </div>

CSS:

.dropdown ul {
  position: absolute;
  background-color: white;
  width: 100%;
  height: 110px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-direction: column;
  border-radius: 20px;
  opacity: 0;
  pointer-events: none;
  transition: all 0.4s ease;
  transform: translateY(5px);
}
.dropdown li {
  width: 100%;
  height: 100%;
  justify-content: space-around;
  align-items: center;
  display: flex;
}

.dropdown a {
  text-decoration: none;
  color: black;
}

.dropdown li:hover {
  background-color: rgba(201, 200, 200, 0.692);
}

.dropbtn:focus + ul {
  opacity: 1;
  pointer-events: all;
}

Upvotes: 0

Views: 587

Answers (1)

Bumhan Yu
Bumhan Yu

Reputation: 2307

Use select & option tags — instead of ul & li tags

HTML has its native dropdown select element, which will not only help you ensure accessibility and usability but also make it easy to style and parse its values. See this MDN page: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select

In your case, your HTML markup can be adjusted to something like...

<label for="genre-select">Select a Genre!:</label>
<select name="genre" id="genre-select">
  <option value="">Select...</option>
  <option value="metal">Metal</option>
  <option value="rock">Rock</option>
  <option value="pop">Pop</option>
</select>

Query options and read their values in JavaScript

Something like...

const dropdown = document.querySelector('select#genre-select');

function handleDropdown(e) {
  const val = e.target.value; // Retrieve the value
  console.log(val); // Do whatever you need to do.
}
dropdown.addEventListener('change', handleDropdown);

See this Codepen link for code example.

Upvotes: 1

Related Questions