12. Listening to keyboard and mouse events

Ready to listen for some key codes on your keyboard and some mouse buttons using Vue? Let’s dig deep then! Make sure you read up on “Listening to DOM events and Event modifiers” if you haven’t already. Because this is more of a continuation to what we already saw.

Starting code

Index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Hello Vue!</title>
    <!-- including Vue with development version CDN -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <h2>Welcome</h2>
      <button>Greet</button>
    </div>
    <!-- including index.js file -->
    <script src="index.js"></script>
  </body>
</html>

Index.js

new Vue({
  el: "#app",
  data: {
  },
  // define all custom methods within the 'methods' object
  methods: {
    greet() {
      alert("Hi");
    }
  }
});

Listening to keyboard events

In the developer world, we often listen for the Enter key to make sure we perform the respective action even though the user doesn’t explicitly click on the HTML button that is provided on the page to handle this case. When listening to key events with Vue, we can mention the required key modifiers with the usual v-on directive like so,

Index.html (code snippet)

 <!-- Using key modifiers along with keyboard events -->
<button v-on:keyup.13="greet">greet</button>

Whenever the user releases a key or the key goes up, a keyup event is triggered. In this case, we want to listen for the Enter key in specific and not just any other key. So, let us mention its key code which is 13 by adding a dot after the keyup event. Wondering how I knew that key code? Frequently used ones, usually stay on top of our heads. If not, try https://keycode.info/ to get the keycode of any key on the keyboard. It is pretty cool!

But isn’t it a hassle to remember or google for key codes all the time? Don’t worry! Just like event modifiers such as, .once, .prevent, .self etc., Vue provides us with key modifiers for most of the frequently used keys. The list goes like this,

  • .enter
  • .tab
  • .delete (captures both “Delete” and “Backspace” keys)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

Now, you can safely replace the keycode 13 with the key modifier .enter and it will work like a charm. Focusing on the button and clicking Enter on the keyboard will show an alert message that says, “Hi”.

Sticky Note: Key modifiers work only with keyboard-related events such as keyup. No rocket science or quantum physics stuff here! ?

Custom key modifier aliases

Apart from the key modifiers that get shipped with Vue, you can very well go ahead and set up your own custom aliases for any key codes of your choice. This is done with the global config.keyCodes object.

Add the below line to “index.js” file to enable “v-on:keyup.a”,

Vue.config.keyCodes.a = 65;

Index.html (code snippet)

<button v-on:keyup.a="greet">greet</button>

Here, when the key ‘a’ is released, a keyup event with keycode 65 is fired and the method “greet()” is called. Cakewalk!

More mouse event examples on their way!

In our previous article, we saw the most famous mouse event, THE CLICK EVENT. Let us see one more now, mouseover.

Let’s say, when we hover our mouse pointer over a button, “Hover over me!”, the text “developer” should be displayed.

Add “role” to the Vue instance’s data object and define a method named “showRole” to update this role property to the String, developer. Call this method when the mouseover event is triggered.

Index.js

new Vue({
  el: "#app",
  data: {
    role: ""
  },
  // define all custom methods within the 'methods' object
  methods: {
    showRole() {
      // 'this' keyword refers to the current Vue instance
      this.role = "developer";
    }
  }
});

Index.html (code snippet)

<button v-on:mouseover="showRole">Hover over me!</button>
 {{ role }}

mouseover event

We are not done yet!

Working with the Event object

Remember the native Event object from the JavaScript world? When an event is triggered, the Event object gets created and passed automatically to any method that is being called using the v-on directive. Thanks again to Vue! Let us see some examples to get a hold of this.

The Event object has a “target” method which returns the element that triggers the event and using this along with the element.tagName property returns the element’s HTML tag name.

Index.html (code snippet)

<div>
  <!-- Listening to mouse events -->
  <button v-on:mouseover="showRole">Hover over me!</button>
  {{ role }} 
  <p>{{ "Tag Name:" + tagName }}</p>
</div>

Index.js

new Vue({
  el: "#app",
  data: {
    role: "",
    tagName: ""
  },
  // define all custom methods within the 'methods' object
  methods: {
    showRole() {
      // 'this' keyword refers to the current Vue instance
      this.role = "developer";
      this.tagName = event.target.tagName;
    }
  }
});

Using event.target would return “[object HTMLButtonElement]” and event.target.tagName would return “BUTTON”.

Event object

Passing arguments along with Event object

We know two things for sure by now,

  1. The Event object gets created and passed automatically to the method that is being called when the event is triggered.
  2. It is very easy to pass arguments to these methods by just specifying them within the parenthesis that follow the method name.

What if we want to pass our own arguments along with this automatically created Event object? Can we do that too?

The answer is YES! Absolutely yes!!

The important point to remember here is the naming. Vue stores original DOM Event in a variable named, “$event”. Be careful not to override or misspell as it is a protected name used by Vue.js to understand that this is not a custom argument but the Event object itself.

Let us make these changes to our code.

Index.html (code snippet)

<button v-on:mouseover="showRole('developer', $event)">Hover over me!</button>
{{ role }} 
<p>{{ "Tag Name:" + tagName }}</p>

Index.js (code snippet)

showRole(customRole, event) {
  // 'this' keyword refers to the current Vue instance
  this.role = customRole;
  this.tagName = event.target.tagName;
}

Before I wrap this all up, here is the complete code for you to feast on!

Index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Hello Vue!</title>
    <!-- including Vue with development version CDN -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <h2>Welcome</h2>
      <!-- Using key modifiers with keyboard events -->
      <button v-on:keyup.enter="greet">greet</button>
      <hr/>
      <div>
        <!-- Passing arguments along with original DOM event -->
        <button v-on:mouseover="showRole('developer', $event)">Hover over me!</button>
        {{ role }} 
        <p>{{ "Tag Name:" + tagName }}</p>
      </div>
    </div>
    <!-- including index.js file -->
    <script src="index.js"></script>
  </body>
</html>

Index.js

new Vue({
  el: "#app",
  data: {
    role: "",
    tagName: ""
  },
  // define all custom methods within the 'methods' object
  methods: {
    greet() {
        alert("Hi");
    },
    showRole(customRole, event) {
      // 'this' keyword refers to the current Vue instance
      this.role = customRole;
      this.tagName = event.target.tagName;
    }
  }
});

Thus, we are now able to pass our custom argument along with the automatically created Event object with the $event variable. All the code discussed above along with comments is available in the GitHub repo.

And that brings us to the end of this topic. Have a wonderful day ahead!

Leave A Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.