MultiEvent enables you to use the right event types in touch, mouse, pointer or hybrid environments (Windows 8 devices).
It determines which events are supported in the browser's environment and flags the input used (touch or mouse), including if the input matches the event type. This check for a match is needed due to some mouse events incorrectly firing with a touch input.
Bonus: MultiEvent uses the UMD pattern to support AMD, as well as global implementations.
Give the demo a try.
Download MultiEvent
I've broken the events down onto behaviors: on, off, over, out. This covers the most basic interactions.
I'm not doing any checking for generic pointer events since IE is the only browser that supports them currently. That will need to change as more browsers implement pointer events.
Here's what events are supported in each bucket:
var behaviors = {
on: {
pointer: 'MSPointerDown',
touch: 'touchstart',
mouse: 'click'
},
off: {
pointer: 'MSPointerUp',
touch: 'touchend',
mouse: 'mouseup'
},
over: {
pointer: 'MSPointerOver',
mouse: 'mouseover'
},
out: {
pointer: 'MSPointerOut',
mouse: 'mouseout'
}
}
Instantiate a behavior type:
// returns and array of events
var onMe = multiEvent( 'on' );
Setup the listener (jQuery is assumed):
$( '#some-element' ).on( onMe.events.join( ' ' ), function( e ) {
// Make sure in hybrid enviroments that
// only the first event hanlder is called.
e.preventDefault();
// Tell our instance to generate the needed info about the event.
onMe.resolve( e );
// Flags for input sources
if ( onMe.isTouch ) {
alert( 'Input source was a touch!' );
}
else if ( onMe.isMouse ) {
alert( 'Input source was a mouse!' );
}
// Did the input source match the event that was fired?
// Certain mouse events will incorrectly fire when the
// input was a touch.
if ( onMe.isMatch ) {
alert( 'All is good!' );
}
else {
alert( 'I feel wonky!' )
}
});