Detecting use of touch and mouse, in order to tailor experience based on the user's interactions.
Based on:
Detecting use of touch and mouse, in order to tailor experience based on the user's interactions.
Based on:
// 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 | |
} | |
}); |