onTouch event causing problems with gesture scrolling

Currently, I am utilizing the following Javascript code to implement ontouchstart/move/end callbacks on div elements in an iOS web application. The issue I am facing is that when attempting to scroll through the page, it triggers the ontouchstart event and alters the CSS of the div. What I aim for is to have the CSS changes applied only when a user actually selects the item. My knowledge of Javascript is somewhat basic, so any suggestions on how to modify the code to trigger only when an item is selected would be highly appreciated!

Thank you!

TC

Javascript:

function onclickCallback( event ) {

}

function ontouchstartCallback( event ) {

event.target.className = 'choice_link_selected';
}

function ontouchmoveCallback( event ) {

event.target.className = 'choice_link_selected';
}

function ontouchendCallback( event ) {

event.target.className = 'choice_link';

}

HTML:

<div class="choice_link" onclick="onclickCallback(event);" ontouchstart="ontouchstartCallback(event);" ontouchend="ontouchendCallback(event);" ontouchmove="ontouchmoveCallback(event);">
            <a href="javascript:location.href='test.php'">Test</a>
         </div>

Answer №1

Remember to use the method event.stopPropagation() to halt event bubbling, and also utilize event.preventDefault() to prevent the default handler from executing.

<div id="ctr" class="choice_link">
     <a href="javascript:location.href='test.php'">Test</a>
</div>
<script>
function onTouchStart(event) {
  event.stopPropagation();
  event.preventDefault();
  event.target.className = 'selected';
}

function onTouchEnd(event) {
  event.stopPropagation();
  event.preventDefault();
  event.target.className = '';
}

var ctr = document.getElementById('ctr');
ctr.addEventListener('touchstart', onTouchStart, false);
ctr.addEventListener('touchend', onTouchEnd, false);
</script>

Answer №2

Assuming I've grasped your query correctly:

Enhance ontouchstartCallback:

if(event.touches.length < 1) return;
event.target.touchdata = [event.touches[0].clientX, event.touches[0].clientY];

Substitute the content of ontouchmoveCallback with:

if(event.touches.length < 1) return;
var threshold = 5;
if(event.target.touchdata)
{
    if(Math.abs(event.touches[0].clientX - event.target.touchdata[0]) > threshold
    || Math.abs(event.touches[0].clientY - event.target.touchdata[1]) > threshold)
    {
        event.target.className = 'choice_link';
        event.target.touchdata = false;
    }
}

The purpose of this code:

At the start of a touch event, the X/Y coordinates are linked to the touched DOM element. Then during each movement event, it verifies whether the distance traveled is beyond a specified pixel threshold (set at 5). If it surpasses the threshold, the class reverts early and eliminates the X/Y coordinates as they are no longer necessary.

Answer №3

From my understanding, using the onmousemove handler to switch the className back to its default state is a valid approach. The issue you're experiencing with your button state freezing during iPhone scrolling has more to do with how scrolling interacts with page rendering performance than the specific handling of the button state change.

When you attempt to scroll on a webpage, the system locks interactions to ensure smooth scrolling and prevent conflicts. This can result in the appearance of a frozen page content, making it difficult for your button to revert to its default state mid-scroll.

The behavior you're describing can vary depending on how the scroll action is initiated. If the button div receives a touchmove event before the scrolling begins, it may be able to maintain its updated class. Otherwise, the class will likely only update once the scrolling action is completed.

Some JavaScript touch frameworks address this issue by intercepting touch events, preventing default browser behaviors (such as scrolling), and implementing custom scrolling mechanisms.

While I don't have a definitive solution, I hope this explanation sheds some light on the issue you're facing.

Best of luck with resolving the matter. Take care.

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

Tips for testing a function that calls other functions during unit testing

Exploring jest for the first time to test my REST API has been quite the learning experience, especially when it comes to unit testing the controllers. I'm facing a challenge in testing a function that involves calls to other functions (including npm ...

Obtaining a string value from a parallel array

Apologies for the very basic question, but I'm struggling with this. I have a word. Each letter of the word corresponds to a position in one array, and then returns the character at the same position from a parallel array (basic cipher). Here is my c ...

Displaying and Concealing Divisions

My journey to showing/hiding divs began with piecing together a series of questions: $(document).ready(function(){ $('.box').hide(); $('#categories').onMouseOver(function() { $('.box').hide(); $('#div' + ...

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

Python Scrapy: Extracting live data from dynamic websites

I am attempting to extract data from . The tasks I want to accomplish are as follows: - Choose "Dentist" from the dropdown menu at the top of the page - Click on the search button - Observe that the information at the bottom of the page changes dynamica ...

Why is it that one function does not hold off on execution until Promise.all() is resolved in another function?

I am currently working on a form that allows users to upload files seamlessly. <form @submit.prevent="sendForm" enctype="multipart/form-data"> <input multiple ref="PostFiles" name="PostFiles" type="file" @change="selectFile('add')"> ...

Improving the efficiency of AES decryption in Node.js

I had the idea to build a webpage that would display decrypted data fetched from the server. The app.js file on the server reads and decrypts all the data from a specific folder. var http = require('http'); var path = require('path'); ...

Submission of the form was cancelled, causing a loop to occur

I'm encountering an issue with submitting a file through a standard HTML form. After uploading the file, the process seems to get trapped in a continuous loop where the file keeps uploading repeatedly. The submission of the form is done using jQuery, ...

Exploring jQuery functionalities for dynamic selector input

I have encountered a scenario where I must use dynamic ID's in the format of functionalDescription_IDNUMBER across my page. It is necessary to target specific areas based on the unique IDNUMBER associated with the clicked object. However, I am looking ...

Switch between playing and pausing the mp3 audio in the Next application by using the toggle

I am currently working on my website and I have been trying to add a button to the bottom of the page that can play or pause a song using useSound library. The song starts playing when I click it for the first time, however, I am facing difficulty in stopp ...

Learn how to display only certain elements when triggered by the click of another

I have developed a tab system where each tab contains a unique set of questions and answers. The structure of the tabs is exactly as I envisioned, but I am facing challenges with toggling the display of answers when their respective questions are clicked. ...

What is the best way to verify the API response in YAML format and ensure that it is neither JSON nor Plain Text using JavaScript?

How can I validate YAML data without validating JSON or plain text? I want to ensure that the response is in YAML format and not in JSON or Plain Text. Is there a method to achieve this without inspecting the content-type header? I attempted to use YAML.l ...

Mongoose has a tendency to duplicate the mongodb collection within a single instance

For educational purposes, I am developing a simple todo list application using custom routing functionality. When a user enters a custom route, I check if a document with that name exists in the database. If it does not exist, I create one. However, I am e ...

Switch out all content located after the final character in the URL

In my code, I am using JavaScript to replace the current URL. Here is the snippet: window.location.replace(window.location.href.replace(/\/?$/, '#/view-0')); However, if the URL looks like this: domain.com/#/test or domain.com/#/, it will ...

What is the best way to set up a function to automatically execute on a specific date and time

I am facing a challenge with my website where users can send themselves messages at a chosen date and time. However, I am unsure how to trigger the message delivery at the specified time. While I am aware of CronJobs, they seem more suitable for recurring ...

Is there a way to create an internal link to another HTML templating engine page within Express.js?

I am currently facing an issue with two Pug files, index.pug and search.pug, stored in a /views folder. In my index.pug file, I have the following line of code: a(href="/search.pug") Search In my JavaScript file, I have specified the view engine as P ...

What could be causing this Angular controller to throw the error message "Error: Unknown provider: nProvider <- n"?

Check out the jsFiddle code here: <div ng-app=""> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> {{data.message + " world"}} </div> </div> function FirstCtrl($scope) { ...

Interactive section for user input

I am looking to add a commenting feature to my website that allows for dynamic editing. Essentially, I want users to be able to click on an "Edit" span next to a comment and have it transform into an editable textarea. Once the user makes their changes and ...

experiencing a fault in the Magento platform

Every time I visit my website, I am faced with the following issue (I retrieved this error file from the var folder): a:5:{i:0;s:88:\"Cannot send headers; headers already sent in /home/eyewear/public_html/index.php, line 1\";i:1;s:943:\"# ...

Creating a sliding bottom border effect with CSS when clicked

Is there a way to animate the sliding of the bottom border of a menu item when clicked on? Check out the code below: HTML - <div class="menu"> <div class="menu-item active">menu 1</div> <div class="menu-item">menu 2</ ...