JackJack
JackJack

Reputation: 632

Add keyboard event listeners in vue

I read the documentation of vue but can't figure out what is the proper way to add keyboard event listener to my app. It just shows how to add one for input elements. I have something like:

<div>
  <p>Some content</p>
  <button>Go left</button>
  <button>Go right</button>
</div>

I want to add an keyboard event listener so that when a user presses ← it goes left and → goes right. It works for the button event listener, but I don't know how to make it work for keyboard.

Should I do document.addEventListener() or window.addEventListener()? I don't need the event listener for the whole app, just for that div.

Upvotes: 2

Views: 10145

Answers (2)

Ajit
Ajit

Reputation: 905

See this JS Fiddle.

Keyboard events work only when you have focus on that element. So having focus on whole <div> and having keyboard events can help. This also eliminates any need of those two left-right buttons. Elements like <button> and <a> have the ability to get focused, <div> doesn't. So we manually need to add tab index to it.

Learn more about tab index from here.

Upvotes: 2

Husam Elbashir
Husam Elbashir

Reputation: 7177

It does work as expected. You just have to make sure your button is focused.

new Vue({
  el: "#app",
  methods: {
  	squack: function(text){
    	alert(text)
    }
  },
  directives: {
    focus: {
      inserted(el) {
        el.focus()
      }
    }
  }
})
<div id="app">
<div>
  <p>Some content</p>
  <button @keyup.left="squack('left button clicked')" v-focus>Go left</button>
  <button @keyup.right="squack('right button clicked')">Go right</button>
</div>
</div>

See this JSFiddle for example. Make sure you shift focus between buttons with Tab / Shift+Tab.

Upvotes: 2

Related Questions