Edgardo Rodriguez
Edgardo Rodriguez

Reputation: 171

Focus option without select the value in the option list

I have a requirement which is based on open a "Select" with a lot of options but it should start the selection in the half of the list without select that value in which the component was started

<select> 
   <option value="1">value 1</option> 
   <option value="2">value 2</option> 
   <option value="3">value 3</option> 
   <option value="4">value 4</option> 
   <option value="5">value 5</option> 
   <option value="6">value 6</option>
   <option value="7">value 7</option> 
   <option value="8">value 8</option> 
   <option value="9">value 9</option> 
   <option value="10">value 10</option>

When the user opens the list it should start in the middle without select that option, see how the middle option is just focused but not selected:

enter image description here

It's there any way to achieve this using jQuery?

Upvotes: 1

Views: 1168

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206342

Disclaimer: Styling <select> is tricky business. Tested in Chrome, FF, Edge, Windows10

document.querySelectorAll("select[size]").forEach(EL => {
  
  const h = EL.scrollHeight / EL.options.length; // option height
  const i = Math.floor(EL.options.length / 2); // Index of the half-way option
  const s = Math.floor(EL.size / 2); // Get the size (also half-way)
  
  EL.options[i].classList.add("highlight"); // (PS: this is bad UX)
  EL.scroll(0, h * (i - s));
});
select option.highlight {
  background: #0bf;
  color: #fff;
}
<select size="3">
  <option value="1">value 1</option>
  <option value="2">value 2</option>
  <option value="3">value 3</option>
  <option value="4">value 4</option>
  <option value="5">value 5</option>
  <option value="6">value 6</option>
  <option value="7">value 7</option>
  <option value="8">value 8</option>
  <option value="9">value 9</option>
  <option value="10">value 10</option>
</select>

NOTE: The CSS-.highlight option might be a really bad UI and lead to people thinking that that option is actually selected while it's clearly not.
Avoid doing stuff that users are not used to see in the web world.

Therefore: instead of doing

EL.options[i].classList.add("highlight"); // (PS: this is bad UX)

rather do:

EL.options[i].selected = true;

Upvotes: 3

Related Questions