Keyboard button clicks with Space and Enter behave differently
- Published at
- Updated at
- Reading time
- 1min
Whenever you add a JavaScript click handler to DOM elements other than the good old button
, you should ask yourself if you're using the correct element. Semantic HTML provides additional functionality to assistive technology and it's usually more accessible than "clickable div soup".
Buttons come with keyboard accessibility features built-in. They're focusable and can be clicked by pressing Enter
or Space
.
But did you know that the two keyboard clicks behave differently?
Enter
clicks a focused button on press (keydown
) and when held, it clicks indefinitelySpace
clicks a focused button on release (keyup
) and won't fire multiple times when held
🤯
If you handroll click functionality (I'm not saying you should — most of the time a button
should do it!), reimplementing "this simple button" has more nuance than slapping a "click" handler on it to it.
I found this little fun fact on Adrian's blog. Check out the post to learn more and see this click behavior in action.
Join 5.5k readers and learn something new every week with Web Weekly.