Fellow Stranger Fellow Stranger - 1 year ago 65
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)?

Answer Source

Here is a basic example of how you could do this: http://jsfiddle.net/4CrES/2/

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download