Skip to content

TIL: Capture keyboard events on a div

Make a non-input element focusable before handling keyboard events in Vue.

1 min read

A div must be focusable before it can receive keyboard events. Set tabindex="0" to include it in the document's natural tab order, then attach a Vue keyboard listener:

HTML
<div tabindex="0" @keydown.esc="doSomething()">
Press Escape while this area has focus.
</div>

Avoid a positive tabindex, such as tabindex="1", because it creates a custom focus order that can make keyboard navigation unpredictable. Use keydown or keyup; the keypress event is deprecated.

If the element performs an action, prefer a native button. For a genuinely custom interactive widget, also provide the appropriate semantic role, accessible name, and expected keyboard behavior.

More posts connected by shared tags.