Home > Net >  Navigate through a dropdown list using keyboard arrow keys
Navigate through a dropdown list using keyboard arrow keys

Time:12-22

Using Vanilla JavaScript (not using any framework), how can I add keyboard navigation to a simple dropdown? By simple dropdown I mean a very basic dropdown such as:

 <div >
     <div>Test Dropdown</div>
     <ul>
         <li>A</li>
         <li>B</li>
         <li>C</li>
     </ul>
 </div>

Alongside with JavaScript, is there any HTML5 solution for this problem (such that the web browser would understand automatically without having to add any ad-hoc logic)?

CodePudding user response:

Just .focus() on it then you can use your keyboard arrows.

document.getElementById("dropdown").focus();
 <label for="dropdown">Choose an option:</label>
 <select  name="dropdown" id="dropdown">

         <option>A</option>
         <option>B</option>
         <option>C</option>
     
</select>

CodePudding user response:

Radios will give you all the native functionality, you can hide the bubbles with appearance: none and put a label immediately after the input for styling.

input[type=radio] {
  display: block;
  appearance: none;
  margin: 0;
  outline: 0;
}

input[type=radio] label {
  display: block;
  width: 100%;
  background-color: green;
}

input[type=radio]:checked label {
  background-color: yellow;
}
<input type="radio" name="radio-group" id="A"/>
<label for="A">A</label>
<input type="radio" name="radio-group" id="B"/>
<label for="B">B</label>
<input type="radio" name="radio-group" id="C"/>
<label for="C">C</label>

appearance support: https://caniuse.com/?search=appearance

Note that the for property of the label being the same as the id of the input is what allows you to click the label to select the hidden radio.


You can put any html elements in the label tag to fully customize

input[type='radio'] {
  display: block;
  appearance: none;
  margin: 0;
  outline: 0;
}

input[type='radio']   label {
  display: block;
  width: 100%;
  background-color: lightblue;
  margin-top: 4px;
  overflow: auto;
}

input[type='radio']:checked   label {
  background-color: yellow;
}

.a {
  width: min-content;
  color: red;
  border: 2px solid red;
  padding: 10px;
  margin: 10px;
}

.b {
  width: min-content;
  color: blue;
  border: 2px solid blue;
  padding: 20px;
  margin: 20px;
  margin-left: auto;
}

.c {
  width: min-content;
  color: green;
  border: 2px solid green;
  padding: 40px;
  margin: 40px;
  margin-left: auto;
  margin-right: auto;
}
<input type="radio" name="radio-group" id="A"/>
<label for="A"><div >A</div></label>
<input type="radio" name="radio-group" id="B"/>
<label for="B"><div >B</div></label>
<input type="radio" name="radio-group" id="C"/>
<label for="C"><div >C</div></label>

  • Related