• Home
  • Articles
  • Mobile and Desktop Event Normalization with pointer.js
 
2
0
0

Mobile and Desktop Event Normalization with pointer.js

The mobile revolution brought in a variety of new challenges, one being interaction and event handling.  We have a set of new touch events and the traditional desktop events, and click events work on both devices, but mousemove and touchmove aren’t always in sync, and there are a number of other nuances you run into with different devices.  That’s why Mozilla’s uber-talented Web Developer Potch created pointer.js, a utility to help developers more easily manage events across devices.

pointer.js Documentation

The pointer.js documentation explains the project as well and simply as it should, so I wont reinvent the wheel.  Straight from the docs:

Types of Events

The following events are generated:

  • pointerdown: based on mousedown/touchstart
  • pointerup: based on mouseup/touchend
  • pointermove: based on mousemove/touchmove
  • pointerleave: based on mouseout/touchleave
  • pointerclick: a ‘fast click’ event based on a sequence of the above events. Additional heuristics are applied to determine whether or not to generate a pointerclick.

Event Objects

pointer events have the following custom properties:

  • maskedEvent: the event that triggered the pointer event.
  • touch: boolean- is maskedEvent a touch event?
  • mouse: boolean- is maskedEvent a mouse event?
  • x: page-normalized x coordinate of the event.
  • y: page-normalized y coordinate of the event.

Simple APIs are the best APIs, and Potch nailed this one.

pointer.js Usage

Here are a few example usages of pointer.js:

var element = document.getElementById("myElement");

element.addEventListener("pointerdown", function(detailedEvent) {
	// Do something
});

element.addEventListener("pointerleave", function(detailedEvent) {
	// Do something
});

element.addEventListener("pointerclick", function(detailedEvent) {
	// Do something
	if(detailedEvent.mouse) {
		// desktop
	}
	else {
		// mobile
	}
});

Potch wrote the JS such that you are adding custom event listeners in a traditional way via addEventListener.  I also love that Event object is true, not a new object that provides the original event as one property.  The additional information added to the object is useful in identifying the platform and which event was actually fired.

Event normalization was one of the original reasons for the first event frameworks…and they didn’t even have to deal with mobile devices!  Potch has done well with this event normalization utility and I can’t wait to use it on my next redesign!

Read the full article at: Mobile and Desktop Event Normalization with pointer.js

Treehouse

Sencha Conference

Discussion

-