Skip to content

Instantly share code, notes, and snippets.

@mwheeler
Created November 14, 2012 02:04
Show Gist options
  • Save mwheeler/4069816 to your computer and use it in GitHub Desktop.
Save mwheeler/4069816 to your computer and use it in GitHub Desktop.
Double tap jQuery plugin
var DoubleTap =
{
touchStart: function(event)
{
this.touched = true;
},
touchEnd: function(event)
{
if(!this.touched)
{
return;
}
var now = Date.now();
var element = $(event.target);
var delay = element.data('DoubleTapDelay');
var dblTapTimeout = element.data('dblTapTimeout');
var lastTouch = element.data('lastTouch');
if(lastTouch)
{
//var delta = now - lastTouch;
element.removeData('lastTouch');
// Clear timeout
clearTimeout(dblTapTimeout);
var onDoubleTapCallback = element.data('onDoubleTapCallback');
if(onDoubleTapCallback)
{
onDoubleTapCallback.bind(element[0])(event);
}
}
else
{
element.data('lastTouch', now);
// TODO: Need visual confirmation of a click...
// highlight?
var timeout_handle = setTimeout(
function()
{
element.removeData('lastTouch');
var onSingleTapCallback = $(event.target).data('onSingleTapCallback');
if(onSingleTapCallback)
{
onSingleTapCallback.bind(element[0])(event);
}
},
delay
);
element.data('dblTapTimeout', timeout_handle);
}
// Remove ontouchend event (will be re-added ontouchstart if a double tap occurs)
this.touched = false;
},
touchCancel: function(event)
{
$(event.target).removeData('dblTapTimeout');
$(event.target).removeData('lastTouch');
this.touched = false;
},
touchMove: function(event)
{
$(event.target).removeData('dblTapTimeout');
$(event.target).removeData('lastTouch');
this.touched = false;
},
};
jQuery.fn.doubletap = function(onDoubleTapCallback, onSingleTapCallback, delay)
{
delay = (delay === undefined? 300 : delay);
$(this).data('DoubleTapDelay', delay);
$(this).data('onDoubleTapCallback', onDoubleTapCallback);
$(this).data('onSingleTapCallback', onSingleTapCallback);
$(this).on('touchstart', DoubleTap.touchStart);
$(this).on('touchend', DoubleTap.touchEnd);
$(this).on('touchcancel', DoubleTap.touchCancel);
$(this).on('touchmove', DoubleTap.touchMove);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment