A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

Differentiate between keyboard/mouse :focus pseudo-class

Lletnek
2015-08-09

CSS & JavaScript…

It would be useful if there were some way with CSS and/or JavaScript to determine whether a focus event/state was triggered by mouse click, or keyboard.

I often have an issue where I’ll click a button to submit a form, JS validation fails and prevents the form from submitting. But we’re left with the input button in :focus-ed state.

So we’re left with either of the following situations…

I remove the focus state, and we no longer get one. Keyboard users suffer, whether that’s someone who’s unable to use a mouse, or simply just tabbing through the form for ease.

Or, I leave the focus state, and get stuck with it when validation fails or I tragically trigger .blur() on the button to get rid.

Thoughts? Solutions I’m unaware of (probably)?

Suggested solution perhaps…

input:focus-keyboard, input:focus-pointer?

MT
2015-08-09

Focus first invalid field on validation fail?

Lletnek
2015-08-11

I prefer not to alter the focus for a user. It’s unexpected and can be confusing for screen readers to suddenly be thrust into a form field. It’s not ideal, but it would be useful in certain circumstances.

Pontus
2015-08-12

If you’re open to using a library, ally.js gives you this option. I agree that it would be beneficial to be able to differentiate between the two focus sources natively, though. It’s quite common in my experience that different styles makes sense usability-wise for the different navigation methods.