Get the 2024 Yearly Goals and Progress Tracker Notion Template for FREE!

Understanding Vue.js touch events for Android and iOS

Posted on: Jan 14, 2023

8 mins read

Originally published at blog.logrocket.com

Understanding Vue.js touch events for Android and iOS

Vue.js is one of the popular frontend JavaScript frameworks that helps us build straightforward and fast UIs and SPAs. It also allows us to extend our HTML by using HTML attributes, known as directives. These directives can be in-built by Vue.js, or they can be custom directives predefined by the user.

For this article, we will discuss touch events. Touch events are triggered by users on touchscreen devices like mobile phones or tablets. This article will explain what touch events are, the types of touch events, and how to implement touch events in Vue.js.

Let's get started.

What are touch events?

Touch events can interpret pointer activities from a finger or stylus on touch surfaces like touch screens or trackpads. They listen for touch points or interactions between the user and the touch surface, including when the user's finger touches, moves, or leaves the screen. They do not work on non-touchscreen devices.

Touch events are like mouse events when a user interacts with a screen using a pointing device, such as a mouse or joystick. Unlike mouse events, which listen for interactions happening in the same instance, touch events can listen for simultaneous or multi-touch interactions. For example, they can listen for two-finger gestures like pinching or an advanced movement like flickering.

The event starts when the pointer touches the surface and ends when the pointer leaves. During this event, an application receives all the properties relating to the touch events during the start, move, and end phases. The properties we can access during any event are:

  • identifier: A unique identifier for a specific event. It is used to track multi-touch events. E.g., pointer 1 = identifier 1, pointer 2 = identifier 2
  • screenX / screenY: The x and y coordinates of the touch pointer in the screen coordinates
  • pageX / pageY: The x and y coordinates of the touch pointer in the page coordinates (including scrolling)
  • clientX / clientY: The x and y coordinates of the touch pointer relative to the browser viewport (not including scrolling)
  • radiusX / radiusY / rotationAngle: They describe the area covered by the touch pointer
  • target: The element touched by the pointer. For example, a p element
  • force: The amount of pressure applied to the surface by the user. It ranges between 0.0 (no pressure) and 1.0 (maximum pressure)

If multi-touch points are active simultaneously, all the properties relating to each touch point are collected and stored in a TouchList array and tracked with the identifier property. Before we listen to touch events, let us understand what some of these events are.

Types of touch events

  • Touchstart: This event is triggered when one or more touch points are on the touch surface
  • Touchmove: This event is triggered when one or more touch points move along the touch surface
  • Touchend: This event is triggered when one or more touch points leave the touch surface
  • Touchcancel: This event is triggered when one or more touch points get disrupted in an implementation-specific manner
  • Tap: This event is triggered when one briefly touches the touch surface
  • DoubleTap: This event is triggered when one rapidly touches the touch surface twice
  • Drag: This event is triggered when one drags a touch point from one point to another over the surface without losing contact
  • Flick/Swipe: This event is triggered when one quickly brushes the surface

There are a lot of interactions that can happen on a touch surface. This article will focus on the most common ones, which are the events users do regularly; tap, drag, swipe, and press. You can check these Touch Gesture Cards created by Luke Wroblewski to have an overview of the other interactions and their functionalities.

Listening for Touch Events

Listening for touch events is the same as listening for any event on an element. You add an event listener relating to the touch event you want to listen for and then call the desired function when that event is triggered. Here's an example:

html
<body>
<p>This is a paragraph</p>
<script>
document.querySelector("p").addEventListener("touchstart", myFunction);
function myFunction(e) {
console.log(e.touches, e.type);
}
</script>
</body>

You can also listen for touch events on any mobile browser and iOS or Android.

Listening for touch events in Vue.js

Listening for touch events in Vue.js is the same process as listening for any event in Vue.js. You add an event listener relating to the touch event you want to listen for and call the function you want to run when that event is triggered.

js
<MyComponent
@touchstart="startDrag(item)"
@touchmove="moveDrag(item)"
@touchend="endDrag(item)"
/>
...
methods: {
startDrag(item) {
// do something on touchstart
},
moveDrag(item) {
// do something on touchmove
},
endDrag(item) {
// do something on touchend
},
},

And as I mentioned earlier, the web browser only gives us access to the touchstart, touchend, touchmove, and touchcancel events. You need to write a custom function to listen to custom touch events. Luckily for us, we have a few npm packages to choose from that already handle these event functions for us — the vue3-touch-events and hammer.js plugins. We will use the vue3-touch-events package in this article.

Creating custom touch events in Vue.js

The vue3-touch-events package lets us listen for events like tap, swipe, hold, and drag on any HTML DOM element in Vue 3. If you are using Vue 2, then you would use the vue2-touch-events package.

Installing vue3-touch-events in Vue 3

First, create your Vue.js app by opening your terminal and running the command vue create touch-events, then install the vue3-touch-events package using the command yarn add vue3-touch-events or npm install vue3-touch-events; depending on the package manager you use.

Open the app in your preferred code editor and run the command yarn serve or npm run dev to view the app in your browser.

Creating basic touch events

In your App.vue file, replace its current code with the following:

js
<template>
<button
class="btn"
@touchstart="nameCurrentEvent('touchstart')"
@touchmove="nameCurrentEvent('touchmove')"
@touchend="nameCurrentEvent('touchend')"
>Touch me</button
>
<p class="output"
>Current Touch Event:
<span class="event">{{ name }}</span>
</p>
</template>
<script>
export default {
name: "App",
data() {
return {
name: "none",
};
},
methods: {
nameCurrentEvent(name) {
this.name = name;
console.log(name);
},
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.btn {
border: 2px solid rgb(71, 197, 255);
background-color: rgb(246, 244, 244);
border-radius: 5px;
width: 150px;
height: 100px;
font-size: 1rem;
margin: auto;
display: flex;
align-items: center;
justify-content: center;
}
.event {
border-bottom: 1px solid rgb(71, 197, 255);
color: rgb(113, 113, 113);
}
</style>

Looking at the code above, we created a button element with three event listeners on it; touchstart, touchmove, and touchend. These will call the same function nameCurrentEvent whenever its event is triggered. The event's name, when triggered, is stored in a variable called name, and the function outputs name on the screen.

Viewing this in our browser, we will have:

alt_text

To view the same web app on your phone simultaneously, copy the Network Url created for you in the terminal where you ran yarn serve and paste the link into your phone browser. The link should look something like http://000.000.00.00/8080.

alt_text

So, in your mobile browser, we will have:

alt_text

Now, interacting with the button on our mobile phone, we should see our name value go from none to touchstart when our finger touches the button. Then, when we move our finger from one point in the button to another, we will see touchmove, and touchend when our finger leaves the screen.

Note that you can only test this code on a touch screen device.

basic-touch-event-vue-js

Customizing the touch events

Using vue3-touch-events to listen to custom events is relatively easy. Since we already installed the plugin, we register the plugin inside our main.js file:

js
import { createApp } from "vue";
import App from "./App.vue";
import Vue3TouchEvents from "vue3-touch-events";
createApp(App).use(Vue3TouchEvents).mount("#app");

In the Vue framework, we add touch events to our elements using the v-touch directive. So let's add the attach functions we want to run when the touch event is triggered. Going into App.js, we modify our current code:

js
<template>
<div class="grid-cntr">
<button
class="btn"
@touchstart="nameCurrentEvent('touchstart')"
@touchmove="nameCurrentEvent('touchmove')"
@touchend="nameCurrentEvent('touchend')"
>Touch me</button
>
<button class="btn" v-touch:tap="onTapItem">Tap me</button>
<button class="btn" v-touch:swipe="onSwipeItem">Swipe any direction</button>
<button class="btn" v-touch:swipe.left="onSwipeLeftItem">Swipe left</button>
<button class="btn" v-touch:drag="onDragItem">Drag me</button>
<button class="btn" v-touch:press="onPressItem">Press me</button></div
>
<p class="output"
>Current Touch Event:
<span class="event">{{ name }}</span>
</p>
</template>
<script>
export default {
name: "App",
data() {
return {
name: "none",
};
},
methods: {
nameCurrentEvent(name) {
this.name = name;
},
onTapItem() {
return (this.name = "tapped");
},
onSwipeItem() {
return (this.name = "swiped");
},
onSwipeLeftItem() {
return (this.name = "swiped left");
},
onDragItem() {
return (this.name = "dragged");
},
onPressItem() {
return (this.name = "pressed");
},
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.grid-cntr {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
max-width: 500px;
margin: auto;
}
.btn {
border: 2px solid rgb(71, 197, 255);
background-color: rgb(246, 244, 244);
border-radius: 5px;
height: 100px;
font-size: 1rem;
margin: 10px;
display: flex;
align-items: center;
justify-content: center;
}
.event {
border-bottom: 1px solid rgb(71, 197, 255);
color: rgb(113, 113, 113);
}
</style>

In the code above, we added five buttons and used v-touch to add tap, swipe, swipe.left, drag, and press. Let's test it on our mobile browser:

custom-touch-event-vue-js

Vue3-touch-events provide other touch events and you can learn more about them here.

Using parameters in vue3-touch-events

Vue3-touch-events also allow us to pass parameters to the event handler. We need to return a delegate to the event handler, and we can pass as many attributes as we need.

So, let's pass a parameter into v-touch:tap and edit onTapItem:

js
<button class="btn" v-touch:tap="onTapItem('onTapItem')">
Tap me
</button>
...
onTapItem(param) {
return function () {
alert("You called the " + param + " touch event.");
};
},

We passed a string as an argument into another string in our function and then alerted the new string to the user.

Using parameters in vue3-touch-events

Conclusion

And that's it on understanding touch events in Vue.js! We discussed what touch events are and the different touch events, including the default browser events and custom events. We also discussed listening for them and using third-party plugins to create and listen for custom touch events.. The codes for this article are available here on GitHub.

Connect With Me

Follow me on X(Twitter), and LinkedIn to stay updated with my latest content.

If you like my notes and want to support me, you can sponsor me on GitHub Sponsor, or you can buy me a virtual ice cream on ByMeACoffee or Selar. I would really appreciate it. 🙏

For other ways to support me, visit my Sponsorship page or Affiliate Links page.

Subscribe to my newsletter 💌

Never miss a beat! Stay updated with my latest tech tutorials, code snippets, how-to guides, productivity tips, personal projects and experiences, and more! 💻📚✨