How to use native JS to implement touch sliding monitoring events

How to use native JS to implement touch sliding monitoring events

Preface

I wrote a small demo today. There is a part involving the logic of swiping left and right. I originally wanted to use a plug-in, but I remembered that I haven’t used native JS to write sliding monitoring for a long time, so I tried to implement it with native JS. After all, reviewing the old can help you learn the new, and at the same time make a record. First post the achieved effect:

Conception

To write a smooth touch sliding event listener, you need to consider the following three aspects of logic:

  • Distance: The sliding distance should be greater than 40
  • Time: The sliding time is less than 0.5 seconds, that is, the finger is pressed, dragged, and released within 500 milliseconds (avoid triggering just by touching the screen)
  • Slide direction:
    • The condition for sliding left and right is: the distance moved on the X axis is greater than the distance moved on the Y axis. If it is positive, it moves to the left, and if it is negative, it moves to the right.
    • The condition for sliding up and down is that the distance moved by the Y axis is greater than the distance moved by the X axis. If it is positive, it moves upward, and if it is negative, it moves downward.

With the basic idea, we can complete the code according to this idea~

Listening events

When it comes to monitoring touch sliding, the following three touch events are naturally used:

1. touchstart Touch start, triggered when a finger clicks the screen (multi-touch can be monitored, and the following fingers will also trigger)

2. touchmove The contact point changes and is continuously triggered when sliding

3. touchend Touch ends, triggered when the finger leaves the screen

Each of these three touch events includes three touch object lists (multi-touch can be implemented based on the touch points):

1. touches: a list of all finger touch points on the current screen

2. targetTouches: List of fingers on the current DOM element

3. changedTouches: List of current event fingers

At the same time, each touch object Touch contains the following properties:

- identifier: unique ID that identifies the touch

- pageX: the x coordinate of the touch point on the page

- pageY: the y coordinate of the touch point on the page

- screenX: the x coordinate of the touch point on the screen

- screenY: the y coordinate of the touch point on the screen

- clientX: the x coordinate of the touch point in the viewport

- clientY: the y coordinate of the touch point in the viewport

- target: the DOM node that was touched

Code Implementation

With the above ideas and the foundation of touch events, we can easily write the code~

let box = document.querySelector('body') // Listener object let startTime = '' // Touch start time let startDistanceX = '' // Touch start X-axis position let startDistanceY = '' // Touch start Y-axis position let endTime = '' // Touch end time let endDistanceX = '' // Touch end X-axis position let endDistanceY = '' // Touch end Y-axis position let moveTime = '' // Touch time let moveDistanceX = '' // Touch move X-axis distance let moveDistanceY = '' // Touch move Y-axis distance box.addEventListener("touchstart", (e) => {
    startTime = new Date().getTime()
    startDistanceX = e.touches[0].screenX
    startDistanceY = e.touches[0].screenY
})
box.addEventListener("touchend", (e) => {
    endTime = new Date().getTime()
    endDistanceX = e.changedTouches[0].screenX
    endDistanceY = e.changedTouches[0].screenY
    moveTime = endTime - startTime
    moveDistanceX = startDistanceX - endDistanceX
    moveDistanceY = startDistanceY - endDistanceY
    console.log(moveDistanceX, moveDistanceY)
    // Determine if the sliding distance exceeds 40 and the time is less than 500 milliseconds if ((Math.abs(moveDistanceX) > 40 || Math.abs(moveDistanceY) > 40) && moveTime < 500) {
        // Determine whether the distance moved on the X axis is greater than the distance moved on the Y axis if (Math.abs(moveDistanceX) > Math.abs(moveDistanceY)) {
        // Left and right console.log(moveDistanceX > 0 ? 'left' : 'right')
        } else {
        // Up and down console.log(moveDistanceY > 0 ? 'up' : 'down')
        }
    }
})

Let’s run it and see:

It can be seen that the touch time will not be triggered if it is greater than 500ms, and the sliding distance will not be triggered if it is less than 40. If it is an angled sliding, the longest moving distance on the XY axis will prevail. Perfectly achieved!

postscript

The front-end framework is developing rapidly, and many people have no pressure to learn the framework directly, so they don’t pay much attention to learning native JS. But no matter how things change, the essence remains the same. The advantage of the framework lies in its design ideas and patterns. If you want to have a deep understanding, you still need to have native JS as a foundation. If you want to go far, you still need to lay a solid foundation. After all, a tall building starts from the ground, right?

This concludes this article on how to use native JS to implement touch sliding monitoring events. For more relevant JS touch sliding monitoring event content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of JavaScript WebAPI, DOM, events and operation element examples
  • Detailed Analysis of Event Bubbling Mechanism in JavaScript
  • Analysis of the event loop mechanism of js
  • Detailed explanation of JS browser event model
  • A brief discussion on event-driven development in JS and Nodejs
  • Summary of event handling in Vue.js front-end framework
  • Detailed explanation of using javascript to handle common events
  • JavaScript event loop case study

<<:  Linux sudo vulnerability could lead to unauthorized privileged access

>>:  Explanation of MySQL's horizontal and vertical table partitioning

Recommend

How to use the jquery editor plugin tinyMCE

Modify the simplified file size and download the ...

How to fix the footer at the bottom of the page (multiple methods)

As a front-end Web engineer, you must have encoun...

Beginners learn some HTML tags (1)

Beginners can learn HTML by understanding some HT...

Is it necessary to create a separate index for the MySQL partition field column?

Preface Everyone knows that the partition field m...

Use viewport in meta tag to define screen css

<meta name="viewport" content="w...

Docker core and specific use of installation

1. What is Docker? (1) Docker is an open source t...

Example of converting JS one-dimensional array into three-dimensional array

Today I saw a friend asking a question in the Q&a...

React implements a highly adaptive virtual list

Table of contents Before transformation: After tr...

Web page layout should consider IE6 compatibility issues

The figure below shows the browser viewing rate i...

Docker memory monitoring and stress testing methods

The Docker container that has been running shows ...

Example code for implementing triangles and arrows through CSS borders

1. CSS Box Model The box includes: margin, border...

JavaScript Timer Details

Table of contents 1. Brief Introduction 2. setInt...

How to use the markdown editor component in Vue3

Table of contents Install Importing components Ba...

Solution to the timeout problem when installing docker-compose with PIP

1: Installation command pip install docker-compos...