How to Detect a Finger Swipe Events in JavaScript

Mehvish Ashiq Feb 02, 2024
  1. Detect Swipe Events in JavaScript Using Android Studio
  2. Detect Swipe Events in JavaScript Using jquery.mobile
  3. Detect Swipe Events in JavaScript Using swipe-listener
How to Detect a Finger Swipe Events in JavaScript

This tutorial teaches you how to detect finger swipe events in JavaScript. We’ll do this task with and without using android studio.

Detect Swipe Events in JavaScript Using Android Studio

The pre-requisites are given below to follow along with this particular example.

  1. Java (download from here).
  2. Android Studio and SDK tools (download from here).

In Android Studio, we will create a new assets folder inside the app folder. Further, we create the www directory inside the assets folder, and this directory contains the index.html and app.js files.

WebView is used to load this index.html file. The project tree and the files created and modified are given below.

Android Studio Project and Files

Example Code (index.html):

<!DOCTYPE html>
<html>
    <head>
        <script src="file:///android_asset/www/app.js"></script>
    <head>
    <body ontouchstart="touchStart(event)" ontouchmove="touchMove(event)"
        ontouchend="touchEnd()">
        <h1>WEBAPP</h1>
    </body>
</html>

Example Code (app.js):

var startX, startY, moveX, moveY;
// here clientX, and clientY means X and Y coordinates
function touchStart(e) {
  startX = e.touches[0].clientX;
  startY = e.touches[0].clientY;
}

function touchMove(e) {
  moveX = e.touches[0].clientX;
  moveY = e.touches[0].clientY;
}
function touchEnd() {
  if (startX + 100 < moveX) {
    console.log('right');
  } else if (startX - 100 > moveX) {
    console.log('left');
  }
  if (startY + 100 < moveY) {
    console.log('down');
  } else if (startY - 100 > moveY) {
    console.log('up');
  }
}

Example Code (MainActivity.java):

package com.example.swipeapplication;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
  @SuppressLint("SetJavaScriptEnabled")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView browser = findViewById(R.id.webview);
    browser.getSettings().setJavaScriptEnabled(true);
    browser.setWebChromeClient(new WebChromeClient());
    browser.loadUrl("file:///android_asset/www/index.html");
  }
}

Example Code (activity_main.xml):

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity">

 <WebView
 android:id="@+id/webview"
 android:layout_width="match_parent"
 android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Output:

Detect Swipe Events in JavaScript Using Android Studio

In this example, we are using touch events to get swipe results. If we swipe down, it shows a message down to let us know.

The ontouchstart event triggers when the user touches the element and the touchend when the user removes their finger from the element. The touchMove event occurs if the user starts moving his/her fingers on the screen.

Detect Swipe Events in JavaScript Using jquery.mobile

The jquery.mobile is a UI (user interface) based on HTML5 to develop responsive web applications.

HTML Code:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-
                1.4.5.min.css">
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
        </script>
    </head>
    <body>
        <div data-role="page" id="page_one">
            <div data-role="header">
                <h1>The Swipe Event</h1>
            </div>
            <div data-role="main" class="ui-content">
                <p style="border:1px solid black;margin:5px; padding: 20px;">
                    Swipe me within the border!
                </p>
            </div>
            <div data-role="footer">
                <h1>Footer Text</h1>
            </div>
        </div>
    </body>
</html>

JavaScript Code:

$(document).on('pagecreate', '#page_one', function() {
  $('p').on('swipeleft', function() {
    alert('You swiped left!');
  });
  $('p').on('swiperight', function() {
    alert('You swiped right!');
  });
});

Output:

Detect Swipe Events in JavaScript Using jquery.mobile

As you can see, we are detecting swiperight and swipeleft events if the user swipes left or right on a paragraph but within the border.

Detect Swipe Events in JavaScript Using swipe-listener

The swipe-listener library lets the web app listen for the swipe gestures. Whenever the DOM element is invoked, this library purely detects swipe events and examines the direction via the directions object.

HTML Code:

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-            1.4.5.min.css">
        <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js">
        </script>
        <script src="https://unpkg.com/swipe-listener@1.2.0/dist/swipe-listener.min.js"             type="text/javascript"></script>
    </head>
    <body>
        <div data-role="page" id="page_one">
            <div data-role="header">
                <h1>The Swipe Event</h1>
            </div>
            <div data-role="main" class="ui-content">
               <p style="border:1px solid black;margin:5px; padding: 20px;">
                    Swipe me within the border!
                </p>
            </div>
            <div data-role="footer">
                <h1>Footer Text</h1>
            </div>
        </div>
    </body>
</html>

JavaScript Code:

var container = document.querySelector('p');
var listener = SwipeListener(container);
container.addEventListener('swipe', function(e) {
  console.log(e.detail);
});

Output:

Detect Swipe Events in JavaScript Using swipe-listener

In this output, we get many useful properties, for instance, the directions object that tells you in which direction you have swiped.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook