Capture “tap” event with pure JavaScript

后端 未结 4 387
囚心锁ツ
囚心锁ツ 2020-12-23 16:20

How can I capture a user\'s \"tap\" event with pure JS? I cannot use any libraries, unfortunately.

相关标签:
4条回答
  • 2020-12-23 17:12

    There are touchstart, touchend and other events. You can add event listeners for them in this way:

    var el = document.getElementById('test');
    el.addEventListener('touchstart', touchHandler);
    

    More information about native DOM events you can find on MDN webstite.

    0 讨论(0)
  • 2020-12-23 17:17

    This is not my code but I can't remember where I got it from, used successfully. It uses jQuery but no extra libraries or plugins for the tap handling itself.

    $.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
    }
    

    I used this for a project exclusively for iPad, so might need tweaking to work for desktop and tablet together.

    0 讨论(0)
  • 2020-12-23 17:18

    The click event is triggered on mouse click as well as on a touch click.

    The touchstart event is triggered when the screen is touched.

    The touchend event is triggered when the touch ends. If the default action is prevented, a click event will not trigger.

    http://www.w3.org/TR/touch-events/

    0 讨论(0)
  • 2020-12-23 17:20

    I wrote a little script myself. It's not in pure-JS, but works fine for me. It prevents executing the script on scrolling, meaning the script only fires on a 'tap'-event.

    $(element)
            .on('touchstart', function () {
                $(this).data('moved', '0');
            })
            .on('touchmove', function () {
                $(this).data('moved', '1');
            })
            .on('touchend', function () {
                if($(this).data('moved') == 0){
                    // HERE YOUR CODE TO EXECUTE ON TAP-EVENT
                }
            });
    
    0 讨论(0)
提交回复
热议问题