Skip to content

Instantly share code, notes, and snippets.

@jacobmllr95
Last active December 22, 2016 15:18
Show Gist options
  • Save jacobmllr95/208d9aac738cf1ff4631eaed849e91e8 to your computer and use it in GitHub Desktop.
Save jacobmllr95/208d9aac738cf1ff4631eaed849e91e8 to your computer and use it in GitHub Desktop.
jQuery Taphold Event
(function($) {
$.event.special.taphold = {
tapholdThreshold: 750,
setup: function(data) {
var $this = $(this);
var tapholdThreshold = !isNaN(parseFloat(data)) ?
data : $.event.special.taphold.tapholdThreshold;
var timeout;
var isDefaultPrevented = false;
var isPropagationStopped = false;
var isImmediatePropagationStopped = false;
$this.on('mousedown.th touchstart.th', function(event) {
var $element = $(this);
timeout = setTimeout(function() {
var tapholdEvent = $.extend(event, $.Event('taphold'));
$element.trigger(tapholdEvent);
if (tapholdEvent.isDefaultPrevented()) {
isDefaultPrevented = true;
}
if (tapholdEvent.isPropagationStopped()) {
isPropagationStopped = true;
}
if (tapholdEvent.isImmediatePropagationStopped()) {
isImmediatePropagationStopped = true;
}
}, tapholdThreshold);
});
$this.on('click.th', function(event) {
if (isDefaultPrevented) {
event.preventDefault();
}
if (isPropagationStopped) {
event.stopPropagation();
}
if (isImmediatePropagationStopped) {
event.stopImmediatePropagation();
}
});
$this.on('mouseup.th touchend.th', function() {
clearTimeout(timeout);
setTimeout(function() {
isDefaultPrevented = false;
isPropagationStopped = false;
isImmediatePropagationStopped = false;
});
});
},
teardown: function() {
$(this).off('mousedown.th mouseup.th click.th touchstart.th touchend.th');
}
}
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment