Skip to content

Instantly share code, notes, and snippets.

@theverything
Created August 2, 2014 20:53
Show Gist options
  • Save theverything/b9a5f016305bd70c3425 to your computer and use it in GitHub Desktop.
Save theverything/b9a5f016305bd70c3425 to your computer and use it in GitHub Desktop.
tap.js
var lastScroll = 0;
function onScroll(e) {
lastScroll = window.pageYOffset;
}
window.addEventListener('scroll', onScroll, false);
function NoClickDelay(el) {
if ('ontouchstart' in window) {
this.element = typeof el === "object" ? el : document.getElementById(el);
this.element.addEventListener('touchstart', this, false);
this.element.addEventListener('click', this, true);
}
}
function highlight(e, nc) {
if (!nc.moved) {
nc.theTarget = document.elementFromPoint(e.targetTouches[0].clientX, e.targetTouches[0].clientY);
if (nc.theTarget.nodeType == 3) nc.theTarget = theTarget.parentNode;
nc.theTarget.className += " pressed";
}
}
function unregister(e, nc) {
nc.theTarget.removeEventListener('touchmove', nc, false);
nc.theTarget.removeEventListener('touchend', nc, false);
nc.theTarget.removeEventListener('touchcancel', nc, false);
if (nc.theTarget) {
nc.theTarget.className = nc.theTarget.className.replace(/ ?pressed/gi, '');
}
}
NoClickDelay.prototype = {
handleEvent: function(e) {
this[e.type](e);
},
touchstart: function(e) {
this.moved = false;
this.element.addEventListener('touchmove', this, false);
this.element.addEventListener('touchend', this, false);
this.element.addEventListener('touchcancel', this, false);
highlight(e, this);
},
touchmove: function(e) {
this.moved = true;
this.theTarget.className = this.theTarget.className.replace(/ ?pressed/gi, '');
},
touchend: function(e) {
e.preventDefault();
unregister(e, this);
if (!this.moved && this.theTarget && Math.abs(window.pageYOffset - lastScroll) < 10) {
var theEvent = document.createEvent('MouseEvents');
theEvent.initEvent('click', true, true);
this.theTarget.dispatchEvent(theEvent);
}
this.theTarget = undefined;
},
touchcancel: function(e) {
unregister(e, this);
this.theTarget = undefined;
},
click: function(e) {
if (this.theTarget === undefined) {
e.stopImmediatePropagation();
e.preventDefault();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment