view raw
Fellow Stranger Fellow Stranger - 6 months ago 30
Javascript Question

Detect whether the intent of a user is to tap or to scroll up/down the page on tactile device

If a user taps (

) outside a popup-div, I want to hide the popup.

But if the user's intent is to scroll/swipe (
), I don't want to hide the popup.

How could the code look like to detect and respond to those two actions (with or without jQuery)?


Here is a basic example of how you could do this:

The logic behind it involves detecting the initial touch time and saving it to a var

touchTime = new Date();

In the touchend handler subtract this time from the current time to get the difference:

var diff = new Date() - touchTime;

Use an if statement to decide whether the touch duration was short enough to consider it a tap, or long enough to consider it a drag.

if (diff < 100){
    //It's a tap
else {
    //Not a quick tap

You could write a more robust implementation by doing a similar difference of the initial touch y position to the final touch y position in the handlers. Another option is to compare the scrollTop of the scrolling area to see if it has been scrolled.