Skip to content
Advertisement

Detecting keyboard button and play sound in vue.js

The code below actually plays sounds on each button click with vue.js.

How is it possible to detect keyboard press and play sound when DOM is ready and not when the buttons are clicked?

for example on enter play sound v-on:keyup.13="playSound('path/to/mp3')"

Vue documentation mostly explains html attributes, perhaps this is something that needs to be done in JS, i guess. I am new to Vue.js

Vue.js documentation on Event Modifiers

See the codepen.

new Vue({
  el: '#app',
  data: {
    text: ''
  },
  methods: {
    playSound (sound) {
      if(sound) {
        var audio = new Audio(sound);
        audio.play();
      }
    }
  }
});

Advertisement

Answer

When you press a key, the keyboard event will be fired from the active element and bubble upwards. So if you want to handle all key presses regardless of what element has focus, then you will need to register the listener manually in code on, e.g., document.

new Vue({
  el: '#app',
  created() {
    this.onKeyDown = this.onKeyDown.bind(this);
    document.addEventListener('keydown', this.onKeyDown);
  },
  destroyed() {
    document.removeEventListener('keydown', this.onKeyDown);
  },
  methods: {
    playSound (sound) {
      if(sound) {
        var audio = new Audio(sound);
        audio.play();
      }
    },
    onKeyDown(e) {
      switch (e.keyCode) {
        case 65: this.playSound(sound1); break; // 'a' key
        case 66: this.playSound(sound2); break; // 'b' key
      }
    },
  }
});

Codepen

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement