Last active
August 29, 2015 14:08
-
-
Save TheDutchCoder/dffc7a4e79c63bf3cfed to your computer and use it in GitHub Desktop.
Normalizing 'click'-like events
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
/** | |
* Normalize 'click'-like events on different media. | |
* | |
* We keep track of a touch events, which start out as 'clicks', | |
* but will be cancelled on (e.g.) moves. | |
*/ | |
var _click, | |
_clickEvent; | |
// We start by assuming everything is a click (until cancelled). | |
_click = true; | |
// I use '_clickEvent' in my jQuery plugins to use as a trigger. | |
// When a touch has ended, we can check if it was a click or not. | |
_clickEvent = 'ontouchend' in document.documentElement ? | |
'touchend' : | |
'click'; | |
// The start of a touch could be a 'click'. | |
document.addEventListener('touchstart', function() { | |
_click = true; | |
}, false); | |
// The move of a touch cancels the 'click'. | |
document.addEventListener('touchmove', function() { | |
_click = false; | |
}, false); | |
// Optional jQuery tracking for mouse-based devices. | |
// For IE9+ document.addEventListener can safely be used. | |
$(document).on('click', function() { | |
_click = true; | |
}); | |
// Example in JS. | |
document.addEventListener(_clickEvent, function() { | |
// Do something. | |
}, false); | |
// Example in jQuery. | |
$(document).on(_clickEvent, function(event) { | |
// It was indeed a 'click'. | |
if (_click) { | |
// Do something. | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment