Skip to content

Instantly share code, notes, and snippets.

@lqez
Created September 11, 2012 13:44
Show Gist options
  • Save lqez/3698579 to your computer and use it in GitHub Desktop.
Save lqez/3698579 to your computer and use it in GitHub Desktop.
a little bit modified version of jquery.touchToClick.js
/*
* Author: cargomedia.ch
*
* Binds 'touchstart' when binding $.on('click')
* and triggers 'click' when 'touchend' happens without 'touchmove' inbetween.
*/
(function($) {
if (!("ontouchstart" in window)) {
return;
}
var clickbuster = {
isLocked: false,
delayedUnlock: null,
onClick: function(event) {
if (this.isLocked) {
event.stopPropagation();
event.preventDefault();
}
},
lock: function() {
this.isLocked = true;
var clickbuster = this;
this.delayedUnlock = setTimeout(function() {
clickbuster.unlock();
}, 2000);
},
unlock: function() {
this.isLocked = false;
if (this.delayedUnlock) {
window.clearTimeout(this.delayedUnlock);
}
}
};
document.addEventListener('click', function(e) {
clickbuster.onClick(e);
}, true);
$.event.special.click = {
delegateType: "click",
bindType: "click",
setup: function(data, namespaces, eventHandle) {
var element = this;
var touchHandler = {
handleEvent: function(e) {
switch(e.type) {
case 'touchstart': this.onTouchStart(e); break;
case 'touchmove': this.onTouchMove(e); break;
case 'touchend': this.onTouchEnd(e); break;
}
},
onTouchStart: function(e) {
e.stopPropagation();
this.moved = false;
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
},
onTouchMove: function(e) {
this.moved = true;
},
onTouchEnd: function(e) {
element.removeEventListener('touchmove', this, false);
element.removeEventListener('touchend', this, false);
if (!this.moved) {
clickbuster.unlock();
var theEvent = document.createEvent('MouseEvents');
theEvent.initEvent('click', true, true);
e.target.dispatchEvent(theEvent);
/* MODIFIED : preventDefault */
e.preventDefault();
clickbuster.lock();
e.stopPropagation();
}
}
};
/* MODIFIED : do not tease iscroll elements! */
var classList = element.className.split(/\s+/);
for( var i = 0; i < classList.length; i++ )
if( classList[i] == 'iScroll' || classList[i] == 'iscroll' )
return false;
element.addEventListener('touchstart', touchHandler, false);
$(element).data('touchToClick-handler', touchHandler);
return false;
},
teardown: function(namespaces) {
var element = this;
var touchHandler = $(element).data('touchToClick-handler');
element.removeEventListener('touchstart', touchHandler, false);
return false;
}
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment