Vanilla JavaScript Swipe Gesture Detection

For a project I have to implement a swipe gesture recognition. What it should do is detect if a user has swiped left or right on his device – not more, not less.

So I came up with this little script to accomplish this task.

So the seamingly simple task is to check whether a user has swiped left or right in his smartphone browser.

Instead of using jQuery UI for this (why use a chainsaw if you could use a scalpel), I came to the conclusion to write it myself.

Here’s the gist:

 

So you just include the JavaScript file and call the init  function of the swipe  object.

You can use any element as the gestureZone – such as the whole document or, like I did in this example, a div with the ID container.

var gestureZone = document.getElementById('container');
//var gestureZone = document;
swiper.init(gestureZone, function(e) {
    console.log(e)
})

What it does is adding an eventListener to both the touchStart  and touchEnd  events and then calculates the direction and distance travelled.

The script will fire a callback function which gives you an object with both direction  and movedPixels  attributes.

You can also set the minimum pixels a user has to swipe before the callback will be fired (see the minSwipePixels  attribute of the swipe  object).

I hope this will be useful to some of you. If you have any additions or corrections to make to this code, you can either comment on this blog post or directly under the gist on github.

Sample

Try swiping in the gray container with your finger. Open your browser console. It does not work with mouse events :)

Try swiping your finger here…

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.