Coder Social home page Coder Social logo

umanghome / swipe-listener Goto Github PK

View Code? Open in Web Editor NEW
94.0 3.0 10.0 246 KB

Zero-dependency, minimal swipe-gesture listener for the web.

Home Page: https://umanghome.github.io/swipe-listener

License: MIT License

HTML 17.69% JavaScript 76.70% CSS 5.62%
swipe-gestures web javascript event-listener swipe gestures touch

swipe-listener's Introduction

Swipe-Listener

npm version

Zero-dependency, minimal swipe-gesture listener for the web.


What

Swipe-listener is a very minimal library that allows listening for swipe gesture on literally any DOM element. Once invoked with a DOM element, simply listen for swipe event and determine the direction with the directions object.

Example Code

var container = document.querySelector('#container');
var listener = SwipeListener(container);
container.addEventListener('swipe', function (e) {
  var directions = e.detail.directions;
  var x = e.detail.x;
  var y = e.detail.y;

  if (directions.left) {
    console.log('Swiped left.');
  }

  if (directions.right) {
    console.log('Swiped right.');
  }

  if (directions.top) {
    console.log('Swiped top.');
  }

  if (directions.bottom) {
    console.log('Swiped bottom.');
  }

  if (directions.top && directions.right) {
    console.log('Swiped top-right.');
  }

  if (directions.top && directions.left) {
    console.log('Swiped top-left.');
  }

  if (directions.bottom && directions.right) {
    console.log('Swiped bottom-right.');
  }

  if (directions.bottom && directions.left) {
    console.log('Swiped bottom-left.');
  }

  console.log('Started horizontally at', x[0], 'and ended at', x[1]);
  console.log('Started vertically at', y[0], 'and ended at', y[1]);
});

Installation

Browser

<script src="path/to/swipe-listener.min.js" type="text/javascript"></script>
<script>
  var container = document.querySelector('#container');
  var listener = SwipeListener(container);
  container.addEventListener('swipe', function (e) {
    console.log(e.detail);
  });
</script>

Swipe-listener is also available from unpkg: https://unpkg.com/[email protected]/dist/swipe-listener.min.js

Installing using NPM

Install from NPM using npm i --save swipe-listener, then

import SwipeListener from 'swipe-listener';

OR

const SwipeListener = require('swipe-listener');

API

SwipeListener(element, options)

  • element DOM Element on which you want to enable swipe gesture tracking. This is the element on which you will be attacking the swipe event listener.
  • options [Optional] Configuration options (see below)

Listen for swipe event on the element passed. Access details using event.detail. For example, directions can be accessed using event.detail.directions. See events for more events.

Data passed to event.detail:

  • directions (Object)
    • top (Boolean) Signifies a top-swipe.
    • right (Boolean) Signifies a right-swipe.
    • bottom (Boolean) Signifies a bottom-swipe.
    • left (Boolean) Signifies a left-swipe.
  • x (Array) Array containing two elements: starting and ending x-coords.
  • y (Array) Array containing two elements: starting and ending y-coords.
  • touch (Boolean) Whether or not TouchEvent was used for this particular event.

Note that multiple directions can be true at one. In case of a top-left swipe, directions.top and directions.left will both be true.

Options

Key Description Default value
minHorizontal Minimum number of horizontal pixels travelled for the gesture to be considered as a left or right swipe. 10
minVertical Minimum number of vertical pixels travelled for the gesture to be considered as a top or bottom swipe. 10
deltaHorizontal Maximum difference between the rightmost pixel (right-swipe) or the leftmost pixel (left-swipe) travelled to and the pixel at which the gesture is released. 3
deltaVertical Maximum difference between the bottommost pixel (bottom-swipe) or the topmost pixel (top-swipe) travelled to and the pixel at which the gesture is released. 5
preventScroll Prevents page scrolling when swiping on the DOM element. Can also be specified as a function with the signature (event) => boolean false
lockAxis Enforces only one direction to be true instead of multiple. Selects the direction with the most travel. Is not enforced when the travel is equal. Example: for a top-left swipe, only one of top and left will be true instead of both. true
touch Whether to listen for swipes with touch events true
mouse Whether to listen for swipes with mouse events true

.off()

Turns off the swipe-listener on a given element.

Usage:

var listener = SwipeListener(myElem);
listener.off();

Events

swipe - Emitted once a swipe is performed.

Emitted once a swipe is completed.

event.detail contains

key type description
directions Object Object containing top, left, bottom, right keys. The directions in which the swipe is performed are set to true.
x Array Array of two items: the starting x-coordinate and the ending x-coordinate.
y Array Array of two items: the starting y-coordinate and the ending y-coordinate.
touch Boolean Whether or not TouchEvent was used for this particular event.

swiping - Emitted while a swipe is being performed.

Emitted multiple times during a single swipe.

event.detail contains

key type description
x Array Array of two items: the starting x-coordinate and the ending x-coordinate.
y Array Array of two items: the starting y-coordinate and the ending y-coordinate.
touch Boolean Whether or not TouchEvent was used for this particular event.

swiperelease - Emitted once the swipe is released/completed.

Emitted at the end of the swipe.

event.detail contains

key type description
x Array Array of two items: the starting x-coordinate and the ending x-coordinate.
y Array Array of two items: the starting y-coordinate and the ending y-coordinate.
touch Boolean Whether or not TouchEvent was used for this particular event.

swipecancel - Emitted if the swipe-distance did not meet minimum travel-distance.

Emitted at the end of the swipe.

event.detail contains

key type description
x Array Array of two items: the starting x-coordinate and the ending x-coordinate.
y Array Array of two items: the starting y-coordinate and the ending y-coordinate.
touch Boolean Whether or not TouchEvent was used for this particular event.

Misc

  • When lockAxis is false, swipes using the mouse might make multiple directions true even when the travel in a certain direction may not be much. You can work around this by setting lockAxis to true when the page is not being accessed from a touch-enabled device. Or, you can use event.detail.x and event.detail.y to calculate which direction has more travel and consider only that direction. Or, you can increase the values of minVertical and minHorizontal.
  • TouchEvent is not supported in IE and Edge. Unless you have polyfilled it into the page and it's available as TouchEvent, swipes made using touch will not be detected as touch swipes.

License

MIT License © Umang Galaiya

swipe-listener's People

Contributors

blueberry-jaap avatar brophdawg11 avatar dependabot[bot] avatar nazar-pc avatar sidx1024 avatar umanghome avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

swipe-listener's Issues

`swiping` event support

The swipe event is fired AFTER the user has completed swiping, but what if the use-case requires actions to be performed during the swipe is in progress.

Proposal to add a swiping or a similar event being fired while the swipe is being performed.

Can change swipe to swipecomplete but that will break backward compatibility. Maybe fire both? If swipe is renamed to swipecomplete, use swipeongoing instead of swiping.

IE Compatibility

Is this library IE compatible.
I'm getting an error-
'TouchEvent' is undefined at line 45338
image

Allow preventScroll to be a function?

I was wondering if you would be open to allowing a function to be passed in for preventScroll so the application could make a decision on whether to call preventDefault? I'm still playing around with it a bit, but the current use-case I have is a mobile e-commerce display where there' a main product image that can be swiped left/right to see different images. But setting preventScroll: true makes it such that the user can't scroll by "swiping" up and down on the image either. And when the image takes up most of the vertical real estate, it there's only small sections that the user can use to scroll the image out of the viewport.

I am experimenting locally with using the event details to control whether to preventDefault based on the delta between the x coordinates and y coordinates.

If so, I would be happy to push up a PR once I have something working.

`lockAxis` option.

As per a problem faced by @sidx1024, a lockAxis option makes sense (default: false), which makes only one direction true instead of multiple. For example, instead of top and left both being true, only one of them will be true.

The final direction can be selected by comparing the distances of both directions and using the direction with the most travel.

Request for a Initiating Event Feature

Your application works great, however we are trying to use it for a mobile menu and have a suggestion for you that could be a possible added feature. Currently our mobile menu is just that, will only be used on mobile. Since we are attaching this swipe event to most of the page (so we can open the mobile menu on swipe) it also catches swipe events made by a mouse cursor.

What we were thinking is that maybe you could add a variable to your custom event that checks to see if the user used a mouse to initiate the swipe, or if they used a touch. This would allow us to not assume a users environment based upon screen size and only make this swipe event available if they are physically swiping in a direction instead of using the mouse. Then we could read this variable from the event and decide if we want to continue processing the results of the swipe action.

In the meantime we may just fork and edit as needed, but this could be a great feature to add since you are already using a good custom event to track the other necessary data.

Consider exporting ES6-compatible object

Consider exporting the module as a ES6 compatible module. ES6 module cannot have directly callable functions, but export something in the form of { default: … }.

In this case you probably want backwards compatibility, and do something like this:

  module.exports = SwipeListener;
  module.exports.default = SwipeListener;

Typescript support

Hey thanks for the excellent library! Any chance of adding typescript definitions of the methods and custom event?

Edge compatibility

Hey there!

I used your package with big satisfaction in my meteor.js project until I tried to get it working in a Microsoft Edge browser.

Edge still doesn't understand spread syntax in object literals. So the line 42 in your index.js throws an error.

Make listening to mouse events optional

(Related to issue #5)

There are false positives that appear when using swipe-listener. Specifically, on desktop when selecting/highlighting text, it can register as a swipe event because of swipe-listener listens for mouse events. Would be great to make mouse listening an option that one can disable. In my case, I only need it specifically for mobile/touch-screen enabled devices.

Thanks for your consideration!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.