Last active
January 3, 2016 22:22
-
-
Save yoelfme/d87dd08c81908a021918 to your computer and use it in GitHub Desktop.
Module for prevent the touchstart when scrolling
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
// Declare internals | |
var internals = { | |
startX: null, | |
startY: null, | |
tap: false | |
}; | |
internals.setTap = function () { | |
internals.tap = true; | |
setTimeout(function () { | |
internals.tap = false; | |
}, 500); | |
}; | |
internals.getCoord = function (e, c) { | |
return /touch/.test(e.type) ? (e.originalEvent || e).changedTouches[0]['page' + c] : e['page' + c]; | |
}; | |
// Declare externals | |
var externals = {}; | |
externals.eventType = function () { | |
return document.ontouchstart !== null ? 'click' : 'touchstart'; | |
}; | |
externals.assignClick = function (element, doing) { | |
var eventType = externals.eventType(); | |
switch (eventType) { | |
case 'click': | |
element.on('click', doing); | |
break; | |
case 'touchstart': | |
element.on('touchstart', function (e) { | |
internals.startX = internals.getCoord(e, 'X'); | |
internals.startY = internals.getCoord(e, 'Y'); | |
}).on('touchend', function (e) { | |
// If movement is less than 20px, execute the handler | |
if (Math.abs(internals.getCoord(e, 'X') - internals.startX) < 20 && Math.abs(internals.getCoord(e, 'Y') - internals.startY) < 20) { | |
// Prevent emulated mouse events | |
e.preventDefault(); | |
doing.call(this, e); | |
} | |
internals.setTap(); | |
}).on('click', function (e) { | |
if (! internals.tap) { | |
// If handler was not called on touchend, call it on click; | |
doing.call(this, e); | |
} | |
e.preventDefault(); | |
}) | |
break; | |
} | |
} | |
module.exports = externals; | |
// Example | |
helpers.assignClick($('.elements', function () { | |
console.log('It is OK :) '); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment