Master How To Use Javascript Touch Events

Are you wondering what are the JavaScript touch events? Confused what events to trigger in particular touch-enabled devices?

In this guide, you will definitely know what are the touch events in Javascript along with their purpose. Expect also example programs that demonstrate the touch events usage.

Let’s get started!

What is a JavaScript touch event?

The JavaScript touch event is a type of event that is triggered on touch-enabled devices such as smartphones or tablets, when the user interacts with the screen.

Additionally, these events allow JavaScript code to respond to various touch-based actions, such as tapping, swiping, or pinching.

Touch events are similar to mouse events in JavaScript but are specifically designed to handle touch interactions.

They provide information about the touch points on the screen, including their coordinates and changes in position over time.

This allows developers to create interactive and responsive web applications that can cater to touch-based inputs.

Kinds of JavaScript Touch Events

Here are some of the kinds of JavaScript touch events which commonly used:

EventsDescription
touchstartThis event is triggered when a finger touches the screen.
touchmoveThis event occurs when a finger moves across the screen.
touchendThis event is triggered when a finger is lifted off the screen.
touchcancelThis event is triggered when the touch event is canceled, such as when the touch points move outside the boundaries of the browser window.

Example Programs of touch events in JavaScript

Here are the following examples which demonstrates the javascript touch events.

Example 1: Detecting a Tap

<!DOCTYPE html>
<html>
<head>
  <title>Pinch and Zoom</title>
  <style>
    #myElement {
      width: 200px;
      height: 200px;
      background-color: blue;
      transform-origin: top left;
      transition: transform 0.3s;
    }
  </style>
</head>
<body>
  <div id="myElement"></div>

  <script>
    // Add touch event listeners to an element
    var element = document.getElementById('myElement');
    element.addEventListener('touchstart', function(event) {
      // Prevent default touch behavior
      event.preventDefault();

      // Store initial finger positions
      var touch1 = event.touches[0];
      var touch2 = event.touches[1];
      var initialDistance = getDistance(touch1, touch2);

      // Add touchmove event listener
      element.addEventListener('touchmove', handleTouchMove);
    });

    // Touchmove event handler
    function handleTouchMove(event) {
      // Prevent default touch behavior
      event.preventDefault();

      // Calculate current finger positions and distance
      var newTouch1 = event.touches[0];
      var newTouch2 = event.touches[1];
      var currentDistance = getDistance(newTouch1, newTouch2);

      // Calculate the scale factor
      var scaleFactor = currentDistance / initialDistance;

      // Apply scaling to the element
      element.style.transform = 'scale(' + scaleFactor + ')';
    }

    // Add touchend event listener
    element.addEventListener('touchend', function(event) {
      // Remove touchmove event listener
      element.removeEventListener('touchmove', handleTouchMove);

      // Reset element scale
      element.style.transform = 'scale(1)';
    });

    // Helper function to calculate distance between two touch points
    function getDistance(touch1, touch2) {
      var dx = touch1.clientX - touch2.clientX;
      var dy = touch1.clientY - touch2.clientY;
      return Math.sqrt(dx * dx + dy * dy);
    }
  </script>
</body>
</html>

Let’s consider an example where we have an HTML document containing various elements. One of these elements is a <div> (division) element, which has been assigned an ID of “myElement“.

We’ve set some styling properties for this particular <div> element, such as a blue background color and a size of 100×100 pixels.

Now, we want to add some interactivity to this <div> element. To achieve this, we attach an event listener specifically for the “touchstart” event.

In simpler terms, we want to detect when the user taps on this <div> element using their touch input.

When a tap occurs on the <div>, the “touchstart” event is triggered. To provide a customized behavior, we prevent the default action that usually takes place when a touch event happens. In this case, we don’t want any standard touch-related actions to occur.

After preventing the default touch behavior, we log a message to the console.

This message serves as a way to indicate that a tap has been detected on the <div> element.
By logging this message, we can track and observe the occurrence of taps on this specific element.

Expected Output: When the user taps on the blue div element, the console will display the message “Tap detected!”.

detecting tap

Example 2: Dragging Element

<!DOCTYPE html>
<html>
<head>
  <title>Draggable Element</title>
  <style>
    #myElement {
      width: 100px;
      height: 100px;
      background-color: green;
      position: absolute;
    }
  </style>
</head>
<body>
  <div id="myElement"></div>

  <script>
    // Add touch event listeners to an element
    var element = document.getElementById('myElement');
    element.addEventListener('touchstart', function(event) {
      // Prevent default touch behavior
      event.preventDefault();

      // Get the initial touch position
      var touch = event.touches[0];
      var startX = touch.clientX;
      var startY = touch.clientY;

      // Add touchmove event listener
      element.addEventListener('touchmove', handleTouchMove);
    });

    // Touchmove event handler
    function handleTouchMove(event) {
      // Prevent default touch behavior
      event.preventDefault();

      // Calculate the distance moved
      var touch = event.touches[0];
      var moveX = touch.clientX - startX;
      var moveY = touch.clientY - startY;

      // Update the element's position
      element.style.left = moveX + 'px';
      element.style.top = moveY + 'px';
    }

    // Add touchend event listener
    element.addEventListener('touchend', function(event) {
      // Remove touchmove event listener
      element.removeEventListener('touchmove', handleTouchMove);
    });
  </script>
</body>
</html>

In this example, we have an HTML document with a draggable <div> element (with ID “myElement“) that has a green background and a size of 100×100 pixels.

We apply CSS styles to position it absolutely. We attach touch event listeners to this element. When the user touches the div (touchstart event), we prevent the default touch behavior and store the initial touch position.

We then add a touchmove event listener that tracks the movement of the touch. Inside the touchmove event handler, we calculate the distance moved by subtracting the current touch position from the initial touch position.

We update the element’s position by setting the left and top CSS properties. When the user lifts their finger off the screen (touchend event), we remove the touchmove event listener.

Expected Output: When the user touches the draggable green div element and moves their finger, the element will follow the finger’s movement on the screen.

Dragging Element

Example 3: Pinching And Zooming

<!DOCTYPE html>
<html>
<head>
  <title>Pinch and Zoom</title>
  <style>
    #myElement {
      width: 200px;
      height: 200px;
      background-color: red;
      transform-origin: top left;
      transition: transform 0.3s;
    }
  </style>
</head>
<body>
  <div id="myElement"></div>

  <script>
    // Add touch event listeners to an element
    var element = document.getElementById('myElement');
    element.addEventListener('touchstart', function(event) {
      // Prevent default touch behavior
      event.preventDefault();

      // Store initial finger positions
      var touch1 = event.touches[0];
      var touch2 = event.touches[1];
      var initialDistance = getDistance(touch1, touch2);

      // Add touchmove event listener
      element.addEventListener('touchmove', handleTouchMove);
    });

    // Touchmove event handler
    function handleTouchMove(event) {
      // Prevent default touch behavior
      event.preventDefault();

      // Calculate current finger positions and distance
      var newTouch1 = event.touches[0];
      var newTouch2 = event.touches[1];
      var currentDistance = getDistance(newTouch1, newTouch2);

      // Calculate the scale factor
      var scaleFactor = currentDistance / initialDistance;

      // Apply scaling to the element
      element.style.transform = 'scale(' + scaleFactor + ')';
    }

    // Add touchend event listener
    element.addEventListener('touchend', function(event) {
      // Remove touchmove event listener
      element.removeEventListener('touchmove', handleTouchMove);

      // Reset element scale
      element.style.transform = 'scale(1)';
    });

    // Helper function to calculate distance between two touch points
    function getDistance(touch1, touch2) {
      var dx = touch1.clientX - touch2.clientX;
      var dy = touch1.clientY - touch2.clientY;
      return Math.sqrt(dx * dx + dy * dy);
    }
  </script>
</body>
</html>

In this example, we have an HTML document with a resizable <div> element (with ID “myElement“) that has a red background and a size of 200×200 pixels. We apply CSS styles to set the transform origin and transition for smooth scaling.

We attach touch event listeners to this element. When the user touches the element with two fingers (touchstart event), we prevent the default touch behavior and store the initial positions of both fingers.

We then add a touchmove event listener that tracks the movement of the fingers.

Inside the touchmove event handler, we calculate the current positions of the fingers and the current distance between them using the helper function getDistance().

Based on the change in distance, we calculate a scale factor to determine the amount of scaling to apply to the element. We update the element’s scale using CSS transformation.

When the user lifts both fingers off the screen (touchend event), we remove the touchmove event listener and reset the element’s scale to 1.

Expected Output: When the user touches the resizable red div element with two fingers and moves them closer (pinch), the element will zoom in. Conversely, when the user moves the fingers apart (zoom out), the element will zoom out smoothly due to the CSS transition effect.

pinching and zooming

To learn more about JavaScript functions here are other resources you can check out:

Conclusion

In conclusion, Javascript touch events are crucial as essential tools for web developers looking to create touch-eanabled websites with enhanced user interaction.

By harnessing the power of touch gestures, developers can provide users with intuitive and engaging experiences on a variety of devices.

Whether it’s a simple tap, a swipe, or a complex multi-touch interaction, JavaScript touch events enable developers to unlock the full potential of touchscreen devices and deliver seamless web experiences.

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.

Glay Eliver


Programmer & Technical Writer at PIES IT Solution

Glay Eliver is a programmer and writer at PIES IT Solution, author of over 600 tutorials at itsourcecode.com. Specializes in JavaScript tutorials, Microsoft Office how-tos (Excel, Word, PowerPoint), and Python error debugging covering ImportError, TypeError, AttributeError, ModuleNotFoundError, and JavaScript ReferenceError. Authored several of the site’s highest-traffic Excel and MS Office reference articles.

Expertise: JavaScript · MS Excel · MS Word · MS PowerPoint · Python · Python ImportError · Python TypeError · Python AttributeError · ModuleNotFoundError · JavaScript ReferenceError · Pygame
 · View all posts by Glay Eliver →

Leave a Comment