Search code examples
vue.jskeyboardfocus

Trigger click event by Enter key on div or other non-button in Vue2


Just tabindex="0" is not enough to trigger click event by focusing on element and then pressing Enter key if element is not button/input/link. What else required?

<!--not working, even if the element has focus-->
<div tabindex=0>Trigger click event on me by Enter key!<div>

Solution

  • The only way is to handle the keydown.enter event manually. You only get click events for free with certain elements (buttons, links, etc) because the browser has special behavior for those elements, with a div that won't happen automatically even though you've made it focusable.

    <div tabindex="0" @keydown.enter="handleClick" @click="handleClick">