Explain Codes LogoExplain Codes Logo

Change Select List Option background color on hover

javascript
custom-dropdown
css-box-shadow
javascript-events
Anton ShumikhinbyAnton Shumikhin·Oct 25, 2024
TLDR

Need a quick solution to alter the background color of select list options on hover? The combination of CSS for base styling and JavaScript for event handling works like a charm, as :hover CSS pseudo-class on <option> isn't broadly honored. Here's the brief implementation:

CSS:

.highlight { background-color: lightblue; } /* You can always switch the color to your beloved one ;) */

JavaScript:

const mySelect = document.getElementById('mySelect'); mySelect.addEventListener('mouseover', e => { // Did someone say party? Apply the "highlight" dress code. if(e.target.tagName === 'OPTION') e.target.classList.add('highlight'); }); mySelect.addEventListener('mouseout', e => { // Party ends? Back to casual attire. if(e.target.tagName === 'OPTION') e.target.classList.remove('highlight'); });

This code adds the .highlight class while hovering an option, swapping the background to light blue.

Overcoming style limitations

Styling <select> and its <option> elements can be a tricky business due to browser rendering differences. Many browsers offload the rendering job to OS-level controls leading to CSS :hover failures on <option> tags.

Firefox offers a mild relief allowing some styling using box-shadow. But again, it is not a universal fix.

In Chrome, you can only manipulate the background-color for select:focus > option:checked, but hover is a hit and miss.

Custom dropdown for robust styles

A custom dropdown with a series of ul/li elements imitates hover styles, interaction patterns, and accessibility traits of a select list beautifully. This requires JavaScript to manage the hover events and perform styling.

Advanced Implementation and Browser Compatibility

CSS-based Box Shadow Trick

CSS provides an escape hatch with box shadows to make up for the :hover shortcomings. They can simulate a background change using the inset parameters like 0 0 10px 100px #000 inset. Bear in mind that it's not a guaranteed cross-browser solution.

Power of JavaScript

When CSS limitations stop you in tracks, JavaScript holds the secret key. It can discern hover states and apply styles programmatically to custom dropdown elements.

Going beyond native drop-downs

Going a notch up, custom HTML dropdowns with ul/li mix styled with radio inputs can mimic the select list behavior brilliantly. This approach offers unlimited options for customization and interaction.