DEV Community

Discussion on: 🔥🔥 how to style select input in css

Collapse
 
jameslivesey profile image
James Livesey

Looks really nice, but unfortunately this isn't accessible at all to blind/visually impaired users who use screen readers, or users with reduced motor ability who use either the keyboard only or switches. Would love to see an accessible version! Until then, I'm gonna stick to the default semantic <select>...

Collapse
 
themodernweb profile image
Modern Web • Edited

Ah ! My bad I totally forgot this scenario but no worry you can use this select in your forms you just have to do some changes.

Step 1-. Inside CSS file remove this line

*:focus{
    outline: none;
}
Enter fullscreen mode Exit fullscreen mode

Step 2- Then in JS add focus and blur event to select button

select.onfocus = () => {
    select.classList.add('focus');
}

select.onblur = () => {
    select.classList.remove('focus');
}
Enter fullscreen mode Exit fullscreen mode

Step 3- And last modify window.keypress function little bit.

window.onkeydown = (e) => {
    if(select.className.includes('active') || select.className.includes('focus')){
        if(e.key === 'ArrowDown' && activeOption < options.length - 1){
            e.preventDefault();
            hoverOptions(activeOption + 1);
        } else if(e.key === 'ArrowUp' && activeOption > 0){
            e.preventDefault();
            hoverOptions(activeOption - 1);
        } else if(e.key === 'Enter'){
            e.preventDefault();
            select.classList.remove('active');
            optionsBox.classList.remove('active');
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

And now you can easily access this select button from tab and change options with keys.

I hope you find this helpful.
Thank you.