Last active
August 29, 2015 13:57
-
-
Save davidhellsing/9484466 to your computer and use it in GitHub Desktop.
click:fast - a fast click event alternative that triggers the handler much faster on touch devices (and also prevents click events on swipe/scroll).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.event.special['click:fast'] = { | |
propagate: true, | |
add: function(handleObj) { | |
var getCoords = function(e) { | |
if ( e.touches && e.touches.length ) { | |
var touch = e.touches[0]; | |
return { | |
x: touch.pageX, | |
y: touch.pageY | |
}; | |
} | |
}; | |
var def = { | |
touched: false, | |
touchdown: false, | |
coords: { x:0, y:0 }, | |
evObj: {} | |
}; | |
$(this).data({ | |
clickstate: def, | |
timer: 0 | |
}).on('touchstart.fast', function(e) { | |
window.clearTimeout($(this).data('timer')); | |
$(this).data('clickstate', { | |
touched: true, | |
touchdown: true, | |
coords: getCoords(e.originalEvent), | |
evObj: e | |
}); | |
}).on('touchmove.fast', function(e) { | |
var coords = getCoords(e.originalEvent), | |
state = $(this).data('clickstate'), | |
distance = Math.max( | |
Math.abs(state.coords.x - coords.x), | |
Math.abs(state.coords.y - coords.y) | |
); | |
if ( distance > 6 ) { | |
$(this).data('clickstate', $.extend(state, { | |
touchdown: false | |
})); | |
} | |
}).on('touchend.fast', function(e) { | |
var $this = $(this), | |
state = $this.data('clickstate'); | |
if(state.touchdown) { | |
handleObj.handler.call(this, e); | |
} | |
$this.data('timer', window.setTimeout(function() { | |
$this.data('clickstate', def); | |
}, 400)); | |
}).on('click.fast', function(e) { | |
var state = $(this).data('clickstate'); | |
if ( state.touched ) { | |
return false; | |
} | |
$(this).data('clickstate', def); | |
handleObj.handler.call(this, e); | |
}); | |
}, | |
remove: function() { | |
$(this).off('touchstart.fast touchmove.fast touchend.fast click.fast'); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment