Differentiate between a Click and Swipe/Drag event in React

Cavan Wagg
2 min readJul 22, 2020

--

Photo by AJ Gallagher on Unsplash

Suppose we have a basic carousel header component where the user navigates by swiping (or click and drag). When clicked the carousel will change color.

Simple enough. But what if we don’t want the color change event to register when we are trying to navigate the carousel via swipe? In other words, we don’t want a on-click event to occur while swiping.

First, let us consider what makes a click different from a swipe. Both involve a mousedown and mouseup action but a swipe involves a change in horizontal movement. If we capture the horizontal coordinates at mousedown and mouseup and notice a significant difference we will know that the user is attempting a swipe and not a click.

Let’s break it down…

First we define a function: mouseDownCoords, where we declare a checkForDrag variable equal to the current X-coord of the client. We attach this to the global window object so we can reference it later. We’ll call this function within the onMouseDown event listener on the Slider element.

Next, we’ll define a function: clickOrDrag, where we once again define a variable equal to the current X-coord of the client. Now that we have the x-coordinate both at mouseup and mousedown we’ll compare them.

So if the mouseup and mousedown events have occured within 5 horizontal pixels then we will assume that the user is attempting a click and only a click (not a swipe)¹.

Here’s the final code:

[1] Based on my own testing I found that between 4 and 8 pixels is a good range for comparing the mousedown and mouseup events.

--

--

Cavan Wagg
0 Followers

Front-End dev | Keep growing, keep giving