

The following is a complete demo of the example:

See the Pen Customised Horizontal Swipe by Yon Zubizarreta (@yzubizarreta) on CodePen.

The logic of the example is based on calculating several values that will determine whether the action performed by the user is a horizontal swipe. The objects touchStartCoords and touchEndCoords represent the X and Y coordinates of the event at the beginning and end of the execution, while the variables minDistanceXAxis and maxDistanceYAxis define the limits of the distance covered by the user event. The variable maxAllowedTime defines the time limit allowed by the execution and finally, the variable targetElement represents the element where we’ll delegate the events.

Basically we use two functions to perform the calculation, swipeStart and swipeEnd. The first function swipeStart defines the initial values for the calculation while in the second function swipeEnd we calculate both the limits for the X and Y coordinates and also the time that has passed between the start and end of the process. The resulting values determine if the user action can be defined as a horizontal swipe.

Event delegation is used to launch the functions defined above. The element method addEventListener is used to register listeners for the events mousedown and touchstart. These listeners then call the function swipeStart. The listeners for the events mousemove and touchmove call the function swipeMove and the listeners for mouseup and touchend do the same with the function swipeEnd. As the example has been built using native javascript, I’ve defined the function addMultipleListeners to allow us to register multiple event listeners on a given DOM target element.

In this example there’s another function that we’ve not yet mentioned; namely the function swipeMove. This simple function contains a preventDefault which helps us to control the drag of the target element when the event touchstart has been triggered.

The final javascript code of the example looks like this:

See the Pen Customized Horizontal Swipe by Yon Zubizarreta (@yzubizarreta) on CodePen.

In conclusion, this example can serve you as a starting point for further experimentation with your own implementations of horizontal swipe effects. You can check our implementation on the mobile adaptation of the product page on the Morphsuits website.

Filed under: languages, web


There are no comments.