HomeJavascriptHow To Detect Swipe Direction With Javascript

How To Detect Swipe Direction With Javascript

Hey everyone. Welcome to today’s tutorial. In today’s tutorial, we will learn how to detect swipe direction. To build this project, we need HTML, CSS and Javascript.

This is an intermediate-level javascript project. I would not recommend this project to absolute javascript beginners.
If you are looking for more such projects to improve your javascript skills you can check out this playlist here. This playlist consists of 100+ javascript projects.

The difficulty level of these projects varies from simple to quite complex ones. Therefore this playlist is suitable for all kinds of learners including javascript beginners to javascript experts.

Video Tutorial:

If you are interested to learn by watching the video tutorial instead of reading the blog post you can check out the video down below. Also, subscribe to my youtube channel where I post new tutorials every alternate day.

Project Folder Structure:

Before we start coding, let us create the project folder structure. We create a project folder called – ‘Detect Swipe Direction’. Within this folder, we have three files. These files are index.html, style.css and script.js. The first file is the HTML document, the second file is the stylesheet, and the final file is the script file.

HTML:

We begin with the HTML code. First, copy the code below and paste it into your HTML document. The HTML code consists of div element with class – ‘container’. Inside the container, we have a div with id – ‘touch-area’ and a p element with id – ‘output’.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Detect Swipe Direction</title>
    <!-- Google Fonts -->
    <link
      href="https://fonts.googleapis.com/css2?family=Poppins:wght@600&display=swap"
      rel="stylesheet"
    />
    <!-- Stylesheet -->
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="container">
      <div id="touch-area"></div>
      <p id="output">Swipe Across The Above Area</p>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>

CSS:

Now we style these elements using CSS. For this copy, the code provided to you below and paste it into your stylesheet. Here we use CSS to add dimensions to the touch area and centre it.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  background-color: #9679ff;
}
.container {
  position: absolute;
  transform: translate(-50%, -50%);
  top: 50%;
  left: 50%;
}
#touch-area {
  background-color: #ffffff;
  height: 30em;
  width: 30em;
  border-radius: 0.6em;
}
#output {
  font-family: "Poppins", sans-serif;
  font-size: 1.2em;
  background-color: #ffffff;
  text-align: center;
  padding: 0.8em 0;
  border-radius: 0.3em;
  margin-top: 1em;
}

Javascript:

Next, we add functionality to this project using Javascript. Once again, copy the code provided to you below and paste it into your script file. We do this in eight steps:

  • Initial References
  • Create An Object Of Mouse/Touch Events
  • Function To Detect Whether The Device Is Touch
  • Get Left & Top Of Touch Area
  • Get Exact X & Y Position Of Mouse/ Touch
  • Function When User Starts Swiping Create A Function To Stop Swiping
  • Function On Window Load
let touchArea = document.getElementById("touch-area");
let output = document.getElementById("output");

//Initial mouse X and Y positions are 0

let mouseX,
  initialX = 0;
let mouseY,
  initialY = 0;
let isSwiped;

//Events for touch and mouse
let events = {
  mouse: {
    down: "mousedown",
    move: "mousemove",
    up: "mouseup",
  },
  touch: {
    down: "touchstart",
    move: "touchmove",
    up: "touchend",
  },
};

let deviceType = "";

//Detect touch device

const isTouchDevice = () => {
  try {
    //We try to create TouchEvent (it would fail for desktops and throw error)
    document.createEvent("TouchEvent");
    deviceType = "touch";
    return true;
  } catch (e) {
    deviceType = "mouse";
    return false;
  }
};

//Get left and top of touchArea
let rectLeft = touchArea.getBoundingClientRect().left;
let rectTop = touchArea.getBoundingClientRect().top;

//Get Exact X and Y position of mouse/touch
const getXY = (e) => {
  mouseX = (!isTouchDevice() ? e.pageX : e.touches[0].pageX) - rectLeft;
  mouseY = (!isTouchDevice() ? e.pageY : e.touches[0].pageY) - rectTop;
};

isTouchDevice();

//Start Swipe
touchArea.addEventListener(events[deviceType].down, (event) => {
  isSwiped = true;
  //Get X and Y Position
  getXY(event);
  initialX = mouseX;
  initialY = mouseY;
});

//Mousemove / touchmove
touchArea.addEventListener(events[deviceType].move, (event) => {
  if (!isTouchDevice()) {
    event.preventDefault();
  }
  if (isSwiped) {
    getXY(event);
    let diffX = mouseX - initialX;
    let diffY = mouseY - initialY;
    if (Math.abs(diffY) > Math.abs(diffX)) {
      output.innerText = diffY > 0 ? "Down" : "Up";
    } else {
      output.innerText = diffX > 0 ? "Right" : "Left";
    }
  }
});

//Stop Drawing
touchArea.addEventListener(events[deviceType].up, () => {
  isSwiped = false;
});

touchArea.addEventListener("mouseleave", () => {
  isSwiped = false;
});

window.onload = () => {
  isSwiped = false;
};

That’s it for this tutorial. If you face any issues while creating this project, you can download the source code by clicking on the download button below. Also, if you have any queries, suggestions or feedback you can comment below.
Happy Coding!

Previous articleMCQ – 25/9/22
Next articleMCQ – 27/9/22
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

five × 4 =

Most Popular