Find if device is touch screen then apply touch event instead of click event

前端 未结 4 1715
日久生厌
日久生厌 2020-12-22 01:52

I am creating a phonegap application, but as I came to know that it takes 300MS to trigger click event instead of touchevent.

I don\'t want to apply both event. Is t

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-22 02:15

    This should eliminate the 300ms delay and trigger simulated clicks on desktop and touch devices :

    $('#id').on('mousedown touchstart', function() {
    
        $(this).one('mouseup touchend', function() {
            alert('id was clicked');
       });
    });
    

    If the item has a link in it (normally triggered by click), it would need some adaptation :

    $('#id a').on('mousedown touchstart', function() {
    
        var destination = this.attr('href');
    
        $(this).one('mouseup touchend', function() {
            if (destination) window.location = destination;
        });
    });
    

    Edit - already having an accepted answer, this reply was more of an additional note. But nirmal was correct in the comments that touch devices emulating mouse events might lead to complications. The above code is therefore better suited to use with touch events only.

    To be more complete with this answer, I'll post my approach for handling both touch and mouse events simultaneously. Either sequence will then trigger a custom event named page:tap. Listening for these simulated clicks can then be done as follows:

    $(subject).on('page:tap', function() { ... });
    

    Mouse and touch events are separated and any emulation triggering additional events is prevented by adding a class to body in between touchend and click, removing it again when the latter occurs.

    var root = $('body'), subject = '#example_1, #example_2';
    
    $(document).on('mousedown touchstart', subject, function(e) {
    
      if (e.type == 'mousedown' && e.which != 1) return; // only respond to left clicks
      var mean = $(e.currentTarget);
    
      mean.one('mouseup touchend', function(e) {
        if (e.type == 'touchend' && !root.hasClass('punch')) root.addClass('punch');
        else if (root.hasClass('punch')) return;
        mean.trigger('page:tap');
      });
    })
    .on('click', subject, function() {
    
      root.removeClass('punch');
      return false;
    });
    

    One could also choose to add the class to the active element itself or html for example, that depends a bit on the setup as a whole.

提交回复
热议问题