Using new Force Touch APIs in JavaScript

Note

Skip straight to the Force Touch demo if you’re in a rush.

Force Touch is a brand new input modifier available via JavaScript in Safari 9. Compatible hardware is the Macbook trackpad and Magic Trackpad 21. Standard trackpads are binary; it’s either a click or it’s not. These new trackpads provide an indication of the force or pressure applied along with that click. Those are different from 3D Touch present on the new iPhone 6s that fires touch events instead of click events. Handling those requires separate logic.

As usual, Apple’s Force Touch documentation is complete, illustrated, and relatively dull. The new flowchart for “force click” events is in Figure 6-2. With Safari 9, and on compatible hardware, four new events are fired by click events:

  • webkitmouseforcewillbegin fires before mousedown for a Force Touch enabled event.
  • webkitmouseforcechanged fires when the pressure changes during a mousedown event.
  • webkitmouseforcedown fires when the pressure crosses the threshold of what counts as a forced click. The MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN constant holds this threshold for reference.
  • webkitmouseforceup fires when the pressure stops crossing the threshold of what counts as a force click.

Handling the forcedown and forceup events aren’t necessarily required, they are convenience events triggered when the force on a click crosses the FORCE_AT_FORCE_DOWN value.

Force click graph

This shows timeline of (1) webkitmouseforcewillbegin, (3) webkitmouseforcedown, (4) webkitmouseforceup, (2) mouseup events firing.

Note that these events do not trigger on 3D Touch devices, i.e. iPhone 6s models. Those use touch events that are different.

Monitoring Mouse Events for Force Touch

Checking for events is simple enough with pure JavaScript. Handling these new events with jQuery requires a bit of finesse because the webkitForce property doesn’t get copied up to the jQuery event. It has to be dug out of the originalEvent property as shown below:

function handle_force_change (e) {
    var force = e.originalEvent["webkitForce"]
    ...
}

After that, everything is straight forward with existing event bindings ala obj.on(webkitmouseforcewillbegin, handle_force_begin). In the demo, the force property is kept on the object.

Force Touch JavaScript Demo

Press to generate a mouse down (red background). The object scales if you’re using a Force Touch input device and Safari 9. Demo responds to Force Touch, which are specific new events, not 3D Touch, which passes new information with touch events.

Waiting for force touch...

Like this demo? Check out the gist. Want more information like this in your inbox? Subscribe to updates.


  1. Stunningly expensive trackpad coming in at $129. Typing this to ATP #140 ↩︎

written October 22nd, 2015

October 2015

Can’t find what you’re looking for? Try hitting the home page or viewing all archives.