Hammer.js : How to handle / set tap and doubletap on same elements

和自甴很熟 提交于 2019-12-06 11:20:10

Hammer.js now has a requireFailure method to recognize multiple taps.

Because multiple gestures can be recognized simultaneously and a gesture can be recognized based on the failure of other gestures. Multiple taps on the same element can be easily recognized on this way:

var hammer = new Hammer.Manager(el, {});

var singleTap = new Hammer.Tap({ event: 'singletap' });
var doubleTap = new Hammer.Tap({event: 'doubletap', taps: 2 });
var tripleTap = new Hammer.Tap({event: 'tripletap', taps: 3 });

hammer.add([tripleTap, doubleTap, singleTap]);

tripleTap.recognizeWith([doubleTap, singleTap]);
doubleTap.recognizeWith(singleTap);

doubleTap.requireFailure(tripleTap);
singleTap.requireFailure([tripleTap, doubleTap]);

When a tap gesture requires a failure to be recognized, its recognizer will wait a short period to check that the other gesture has been failed. In this case, you should not assume that its tap gesture event will be fired immediately.

SOURCE: http://hammerjs.github.io/require-failure/

My guess is that the alert is preventing doubletap from being triggered in the first code block... it's kinda messy but you could try something like:

var doubleTapped = false;
$("#W0AM").hammer();
$("#W0AM").on('doubletap', function (event) {
    doubleTapped = true;

    console.log( 'this was a double tap' );
}).on('tap', function (event) {
    setTimeout(function() {
       if(!doubleTapped) {
          console.log( 'this was a single tap' );
       }

       doubleTapped = false;
    }, 500); // This may have to be higher dependant on the speed of the double tap...
});

I'm using jQuery 2.1.0 and Hammer 1.0.10 and Chris's answer almost work but it fires logs tap after logging double tap. I've added a timeout also to the reset of doubleTap back to false and it seems to work out for me.

var doubleTapped = false;
Hammer(document.getElementById("W0AM")).on('doubletap', function (event) {
    doubleTapped = true;

    console.log( 'this was a double tap' );
}).on('tap', function (event) {
    setTimeout(function() {
       if(!doubleTapped) {
          console.log( 'this was a single tap' );
       }

       setTimeout(function() {
           doubleTapped = false;
       }, 500);

    }, 500); // This may have to be higher dependant on the speed of the double tap...
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!