Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  55] [ 4]  / answers: 1 / hits: 33744  / 13 Years ago, sun, january 1, 2012, 12:00:00

I am working with JavaScript and jQuery in an UIWevView on iOS.



I'v added some javascript event handler that allow me to capture a touch-and-hold event to show a message when someone taps an img for some time:



$(document).ready(function() {

var timeoutId = 0;
var messageAppeared = false;

$('img').on('touchstart', function(event) {

event.preventDefault();
timeoutId = setTimeout(function() {

/* Show message ... */
messageAppeared = true;

}, 1000);

}).on('touchend touchcancel', function(event) {

if (messageAppeared) {
event.preventDefault();
} else {
clearTimeout(timeoutId);
}
messageAppeared = false;
});
});


This works well to show the message. I added the two event.preventDefault(); lines to stop imgs inside links to trigger the link.



The problem is: This also seems to prevent drag events to scroll the page from happen normally, so that the user wouldn't be able to scroll when his swipe happens to begin on an img.



How could I disable the default link action without interfering with scrolling?


More From » jquery

 Answers
2

Sometimes you have to ask a question on stack overflow to find the answer yourself. There is indeed a solution to my problem, and it's as follows:



$(document).ready(function() {

var timeoutId = 0;

$('img').on('touchstart', function(event) {

var imgElement = this;

timeoutId = setTimeout(function() {

$(imgElement).one('click', function(event) {
event.preventDefault();
});

/* Show message ... */

}, 1000);

}).on('touchend touchcancel', function(event) {
clearTimeout(timeoutId);
});
});


Explanation




  • No preventDefault() in the touch event handlers. This brings back scrolling behavior (of course).

  • Handle a normal click event once if the message appeared, and prevent it's default action.


[#88291] Thursday, December 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
calicinthias

Total Points: 447
Total Questions: 101
Total Answers: 118

Location: Botswana
Member since Sat, Dec 31, 2022
1 Year ago
calicinthias questions
Sun, Jan 2, 22, 00:00, 2 Years ago
Wed, Jan 13, 21, 00:00, 3 Years ago
Mon, Aug 10, 20, 00:00, 4 Years ago
;