how to unhighlight select element after option is chosed?

Viewed 67

lets say i have a select element in my html and an eventListener in javascript that console.logs some text when i press the space key

document.addEventListener("keyup", myFunc);

function myFunc(event){
      if (event.code === 'Space') {
        console.log("hi");
      }
}
<select id="select">
  <option value="">test</option>
  <option value="">test</option>
  <option value="">test</option>
</select>

When i click on one of the options, the select element automatically closes but its still highlighted. So if i press the space key, it opens the select element instead of executing the console.log function

I have to click outside the select element after i choose an option so i can console.log some text when i press the space key

Is there a way so that i don't have to click outside the select element every time i want to press the key?

3 Answers

Call blur() function on select element at change event listener.

document.addEventListener("keyup", myFunc);
const selectEle = document.getElementById("select");

function myFunc(event){
      if (event.code === 'Space') {
        console.log("hi");
      }
}

selectEle.addEventListener("change", (e) => {
  selectEle.blur();
});
<select id="select">
  <option value="">test</option>
  <option value="">test</option>
  <option value="">test</option>
</select>

Just blur it programatically on change, this.blur():

<select id="select" onchange="this.blur()">
  <option value="">test</option>
  <option value="">test</option>
  <option value="">test</option>
</select>

Related