Written by

Roberto Segura

Category:

Blog

18 November 2019

Last week I wanted to create my own "Powerpoint" app based on Vue.js. One of the challenges was to be able to navigate through slides using a wireless presenter which sends Page Up and Page Down keys to navigate.

There is quite information out there about how to do it but I couldn't find my use case. This article tries to help anybody with the same issue.

The first thing we need to do in our component/view is to attach and remove event listeners on mounted and destroyed events:

 mounted () {
window.addEventListener('keyup', this.handleKeyUp)
},
destroyed () {
window.removeEventListener('keyup', this.handleKeyUp)
},

This tells vue that we want to execute the component `handleKeyUp` method when a `keyup` event happens (when a key of the keyboard is released). It also tells vue to remove the listener when the component is destroyed so we keep things clean.

In my case what I wanted to do is to navigate to previous and next pages when a key is pressed. This is my `handleKeyUp` method:

    handleKeyUp () {
      // Page up
      if (event.keyCode === 33) {
        this.goToPreviousPage()

        return
      }

      // Page down
      if (event.keyCode === 34) {
        this.goToNextPage()
      }
    }

That executes the `goToPreviousPage` method when Page Up is clicked and `goToNextPage` when Page Down is clicked. Those are the keys the wireless presenter sends.

I hope this helped you. Please leave a comment if so!