track-pad tap event in javascript/jquery

5.2k views Asked by At

Is there any way to handle tap from track pad of mac?

I need to handle 'tap' and 'click' on track-pad, especially on mac.

I tried

$.event.special.tap = {
    setup: function(data, namespaces) {
        var $elem = $(this);
        $elem.bind('touchstart', $.event.special.tap.handler)
             .bind('touchmove', $.event.special.tap.handler)
             .bind('touchend', $.event.special.tap.handler);
    },

    teardown: function(namespaces) {
        var $elem = $(this);
        $elem.unbind('touchstart', $.event.special.tap.handler)
             .unbind('touchmove', $.event.special.tap.handler)
             .unbind('touchend', $.event.special.tap.handler);
    },

    handler: function(event) {
        event.preventDefault();
        var $elem = $(this);
        $elem.data(event.type, 1);
        if (event.type === 'touchend' && !$elem.data('touchmove')) {
            event.type = 'tap';
            $.event.handle.apply(this, arguments);
        } else if ($elem.data('touchend')) {
            $elem.removeData('touchstart touchmove touchend');
        }
    }
};

$('.thumb img').bind('tap', function() {
    //bind tap event to an img tag with the class thumb
}

Which didn't work.

How to capture tap event on the track-pad?

1

There are 1 answers

0
linnium On BEST ANSWER

I'm having this same concern. It appears that the trackpad on the MacBook (for example) doesn't fire TouchEvents like an actual touch device would. It is instead converting gestures into MouseEvents.

document.addEventListener('mousewheel', function(e) {
    console.log(e.wheelDelta);
});

document.addEventListener('touchstart', function(e) {
    console.log(e);
});

In the above example, when I attempt to capture the "pinch/zoom" gesture on a trackpad, I'm actually getting back Delta from a scroll wheel as if I'd held down CTRL and then scrolled up or down, returning a wheelDelta value of 120 or -120. Putting event listeners on for 'touchstart' doesn't not write to the console as I prescribe unless it's on a touch device like a tablet or smart phone.

Obviously, the MackBook can detect when you've touched the trackpad since it's able to then detect your movement, but it does not appear to be available through the document.