Prevent the TOUCHMOVE event from being triggered when the finger is no longer touching the element but is still pressed down

I have a parent div with 4 child elements inside. I want to trigger the touchmove event when I touch one of the span elements and move my finger. However, if I move my finger outside of the current span element while still pressing, I want the event to stop.

I've attempted to achieve this by checking if I'm touching a span element or another element, but so far it hasn't been successful. Once I press and move my finger, I can't seem to stop the event until I release my finger.

document.querySelector("#parent").addEventListener('touchmove', (e) => {
    console.log(`pressed ${e.target.getAttribute('data-dir')}`)
});

<div id="parent">
   <span data-dir="3">↑</span>
   <span data-dir="0">→</span>
   <span data-dir="1">↓</span>
   <span data-dir="2">←</span>
</div>

Answer №1

  1. To determine if your finger is inside or outside of the <span>, you can utilize the document.elementFromPoint() API.
  2. If the finger moves outside of the <span>, you can use removeEventListener to stop the event listener during touch interactions.

Here's an example implementation:

const $el = document.querySelector("#parent")
$el.addEventListener('touchstart', function startHandler(e) {
  $el.addEventListener('touchmove', function moveHandler(e) {
      if (document.elementFromPoint(e.touches[0].clientX, e.touches[0].clientY).tagName !== 'SPAN') {
        $el.removeEventListener('touchmove', moveHandler)
      }) else {
        // carry out necessary actions
      }
  });
  $el.addEventListener('touchend', function endHandler(e){
    $el.removeEventListener('touchstart', startHandler)
    $el.removeEventListener('touchmove', moveHandler)
    $el.removeEventListener('touchend', endHandler)
  })
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are you familiar with the Pagination and Card Components offered by Ant Design (antd)?

Can you merge the Pagination feature from antd with Card components to create a layout resembling Pinterest, complete with pagination? The standard Pagination code from https://ant.design/components/pagination/: import { Pagination } from 'antd&apo ...

Effects of jQuery Show / Hide on adjacent select box operations

I created a pair of select boxes where the visibility of one is controlled by the other. Initially, the controlled select box (#select02) works perfectly on page load as long as I don't show/hide it by selecting options in the controlling select box ( ...

Retrieve the processed data from a file using node.js

I have successfully read and parsed my file, however I am facing an issue with retrieving the output string. I want to access this string from a variable assigned to it on the client side. Despite using async series to handle callback functions effective ...

Ensuring the presence of an attribute within an AngularJS Directive

Is it possible to determine if a specific attribute exists in a directive, ideally using isolate scope or the attributes object as a last resort? If we have a directive like this <project status></project>, I would like to display a status ico ...

Is it possible for an AngularJS directive to compile a fresh element that has a second directive assigned to it?

UPDATE: All directives listed below will now require ng-model bindings to be applied in the elements they generate, targeting the controller assigned to the page. The code has been modified to reflect this. I am exploring the creation of dynamic HTML usin ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...

What is the best way to substitute unpredictable dynamic variables on-the-fly?

I am working with a .js file that contains a config structure similar to this: genGetLocations:{ data_url:'restaurants/{var1}/tables/{var2}, } This is just one example. Some configurations may have data_url with more than two dynamic variables. I ...

Encountering a 404 error when attempting to make an Axios post request

Utilizing Axios for fetching data from my backend endpoint has been resulting in a 404 error. Oddly enough, when I manually enter the URI provided in the error message into the browser, it connects successfully and returns an empty object as expected. Her ...

Headers permitted for CORS blocking

Greetings, I have recently developed an API and frontend using React, utilizing axios for making requests. I implemented an authorization header with axios and authenticated it on the PHP server-side. However, there seems to be an issue where the Authoriza ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

Typescript restricts dynamic property access within objects

I'm encountering some difficulties while attempting to access my object property in TypeScript: const sum = (type: string) => { return { status: 'Sum', value: data?[type].sum, }; }; sum('first') Here is a glimps ...

What is the method to obtain the content height of individual pages in Android, with or without the use of JavaScript?

I am facing an issue while trying to retrieve the content height of each webpage consecutively. When I load pages separately, I can successfully get the height of each page. However, when I attempt to fetch the content height continuously for webpages in a ...

Using Vue Axios to load a Laravel view can be a seamless process that

I'm attempting to create a hyperlink to a Laravel view named faq.blade.php from my Vue component. I've tried using axios, and even though it logs the response in the console, the view isn't loading. How can I resolve this issue? FaqControll ...

Guide to configuring environment variables with Script [Node.js]

Is there a way to set an environmental variable using a script in node.js? I have a script that gives me the deployed solidity contract address and I need to use it in my .env file (I am using the dotenv module). I have been trying to figure out a way to ...

Migration unsuccessful due to incompatible peer dependencies detected - Updating Angular to Version 12 was not successful

Currently in the process of upgrading my Angular v11 apps to Angular v12. Encountering an error while attempting to upgrade Angular packages: ng update @angular/core@12 @angular/cli@12 Error: Migration failed due to incompatible peer dependencies The pa ...

Operating PhantomJS in server mode

I am considering using PhantomJS to convert a dynamic AngularJS application into static HTML that can be searched by Google. My plan is to set up a PhantomJS server behind a proxy to handle the ?escaped_fragment requests. While I know that PhantomJS is pri ...

AngularJS - Retrieving an object with a button click

I have an array of objects with names displayed in input fields. I want to update the corresponding object with whatever the user fills in the input field when they click the button. For example, if I enter “abcde” and “pq” in the input fields, th ...

What is the best way to utilize MUI breakpoints for displaying images based on different screen sizes?

I need help displaying an image based on the screen size using MUI breakpoints. I'm struggling to understand how to implement this with MUI. Can someone assist me with the breakpoints? interface EmptyStateProps { title: string; description: string ...

Continue iterating only when all promises have been resolved

My AngularJS requirement involves the following: for (var i = 0, len = self.Scope.data.length; i < len; i++) { var data = self.Scope.data[i]; var self = this; //Executing First asynchronous function self.EcritureService.createNewDa ...

Microphone Malfunction: Abrupt End of Input Detected

I have been experimenting with SpeechRecognition to incorporate microphone functionality into one of my projects. However, when I check the Chrome Console, it displays the error message: Unexpected end of input const speechRecognition = window.webkitS ...