Skip to content

Instantly share code, notes, and snippets.

@catdad
Last active August 29, 2015 14:13
Show Gist options
  • Save catdad/038893779a65326f5d2b to your computer and use it in GitHub Desktop.
Save catdad/038893779a65326f5d2b to your computer and use it in GitHub Desktop.
Detecting use of touch or mouse.
// Determine the event name to use for mouse and touch detection/interaction.
// All browsers will listen to touch.
var clickTouch = "touchend";
if (window.navigator.pointerEnabled) {
// IE11 mobile event, covering mouse and touch
clickTouch += " pointerup";
} else if (window.navigator.msPointerEnabled) {
// IE10 mobile event, covering mouse and touch
clickTouch += " MSPointerUp";
} else {
// all other browser should listen to mouse event
clickTouch += " mouseup";
}
var standardizeClickTouch = function(ev){
if (ev.type.match(/touch/)) {
// always prevent default on touch events, so they do not propagate to clicks
ev.preventDefault();
}
var original = ev.originalEvent ? ev.originalEvent : ev;
if (original.pointerType) {
// This is an MSIE event for a device that has touch controls, or both mouse and touch.
// We will translate this event to match either a regular mouse or regular touch event.
// Change the type to reflect either mouse or touch
var actionType = ev.type.replace(/MSPointer|pointer/, '').toLowerCase(),
pointerType = original.pointerType;
if (pointerType === 'touch') {
switch (actionType) {
case 'up':
actionType = 'end';
break;
case 'down':
actionType = 'start';
}
}
ev.type = pointerType + actionType;
}
return ev;
};
// Usage
$('.selector').on(clickTouch, function(ev){
ev = standardizeClickTouch(ev);
if (ev.type.match(/mouse/i)) {
// do mouse-based action
} else {
// do touch-based action
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment