Input Device Capabilities Sample

Available in Chrome 47+ | View on GitHub | Browse Samples

Background

The Input Device Capabilities API provides information about the capabilities of the physical device responsible for generating an event.

This sample illustrates using UIEvent.sourceCapabilities to obtain the capabilities of the device that triggered the event, and then checks the firesTouchEvents property to determine whether that device can create a TouchEvent. Developers should note that this doesn't necessarily mean the device is a touch screen. For example, stylus and mouse devices typically generate TouchEvents on mobile browsers.

The Touch and Mouse article provides some background on why that knowledge is important for developers.

Live Output


JavaScript Snippet

function uiEventHandler(event) {
  if (event.type === 'mousedown' && event.sourceCapabilities.firesTouchEvents) {
    // If this is a "fake" mousedown event synthesized when tapping on a touchscreen, ignore it.
    return;
  }

  var status = 'The device that triggered this ' + event.type + ' event ' +
    (event.sourceCapabilities.firesTouchEvents ? 'does' : 'does not') +
    ' fire touch events.';
  ChromeSamples.setStatus(status);

  // At this point, you might do something like set a "pressed" style on the button, etc.
}

var button = document.querySelector('#press-me');
button.addEventListener('mousedown', uiEventHandler);
button.addEventListener('touchstart', uiEventHandler);