Touch and Mouse Together

If you have built a web app in the past few years, you've probably had to deal with touch events. In many cases this was limited to handling tap and removing that pesky 300ms delay. However with touch devices becoming more powerful, we now have to implement more complex gestures— gestures that work for both mouse and touch.

In this post we will walk through the process of implementing one such gesture– pan. I will demonstrate this by building a draggable chat-head component.

Note: This will not be the most robust implementation of a draggable component. It is intended to demonstrate how one would handle touch and mouse event simultaneously.

Pan Gesture

The pan gesture can be broken down into three stages: pan start, pan & pan end. On desktop these map quite nicely to the drag event handlers, while for touch devices we will have to use touch events. In the end we have three event handlers:

Pan Start:

onTouchStart={this.onPanStart }
onDragStart={this.onPanStart }

Pan:

onTouchMove={this.onPan }
onDrag={this.onPan }

Pan End:

onTouchEnd={this.onPanEnd }
onDragEnd={this.onPanEnd}>

Pan Start

The onPanStart handler is primarily responsible for setting the dragging state to true.

Pan End

Finally, the onPanEnd handler is responsible for setting the dragging state to false.

onPanEnd=e=>{this.setState({ dragging:false});};

Here is the final result:

Pointer events

The upcoming Pointer events spec aims to unify all input devices – such as a mouse, pen/stylus or touch – into a single model. This will simplify the implementation process for us developers and allow us to provide a good user experience regardless hardware choices.

React & Redux Resources

For more on React, you can check out these informative videos and webinars, as well as previous blog posts. Better yet, we encourage you to inquire about custom training to ramp up your knowledge of the fundamentals and best practices with custom course material designed and delivered to address your immediate needs.