Skip to content

A simple and lightweight JS library to add swipe gestures to your app

Notifications You must be signed in to change notification settings

Jordan-Morrison/Swipey.js

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

17 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Swipey.js

NPM JavaScript Style Guide

A simple and super lightweight (1.29kb) JS library to add swipe gestures to your app.

Installation

Vanilla JS

Download the latest release and include the script in your HTML

<script src="./swipey.js"></script>

React

Install the module into your project

$ npm install swipey.js

Import the module

import swipey from 'swipey.js';

Basic Usage

Vanilla JS

Select the element you wish to be able to swipe on and pass it into swipey.add with a callback function to be fired off when a valid swipe occurs.

let element = document.querySelector(".yourElement");

swipey.add(element, myCallback);

function myCallback(ev){
    //Do some stuff
    console.log(ev);
}

React

Swipey in React works the exact same as Vanilla JS. If you are using functional components then the useRef hook is recommended to select the element you wish to swipe on.

function App() {

    const element = useRef(null);

    swipey.add(element.current, myCallback);

    function myCallback(ev) {
        console.log(ev);
    }

  return (
    <div ref={element} className="App">
        <p>some stuff</p>
    </div>
  );
}

Customization

swipey.add also accepts an optional object for better customization.

The default options are as follows:

{
    vertical: true,
    horizontal: true,
    diagonal: true,
    swipeDistance: 100
}

You may override these defaults by passing your custom options into swipey.add as a 3rd parameter.

In this case the minimum swipe distance will be 25 pixels and will only allow horizontal swipes.

swipey.add(element, myCallback, {
    swipeDistance: 25,
    vertical: false,
    diagonal: false
})

Returned Data

The callback passed into swipey.add will be fired with an event object passed in. The object will contain the following information:

  • swipeLength: The length of the swipe in pixels
  • direction: A string value with the direction of the swipe; up, down, left, right, up-right, up-left, down-right or down-left
  • target: A DOM reference to the element that was swiped on. This is useful for cases where you have multiple swipeable objects and need to know which object was swiped on

An example of what the returned object will look like

{
    swipeLength: 177.55073067405448,
    direction: "down-left",
    target: div.App
}

About

A simple and lightweight JS library to add swipe gestures to your app

Resources

Stars

Watchers

Forks

Packages

No packages published