Giter Site home page Giter Site logo

chrisbateman / impetus Goto Github PK

View Code? Open in Web Editor NEW
487.0 13.0 70.0 182 KB

Agnostic utility for adding momentum to anything. It's like iScroll, except not for scrolling. Supports mouse and touch events.

Home Page: chrisbateman.github.io/impetus

License: MIT License

JavaScript 100.00%

impetus's Introduction

Impetus.js

Add momentum to anything. It's like iScroll, except not for scrolling. Supports mouse and touch events.

Check out the demos on the home page.

Impetus will probably never support anything other than simple momentum. If you need scrolling or touch carousels or anything like that, this probably isn't the tool you're looking for.

Usage

var myImpetus = new Impetus({
    source: myNode,
    update: function(x, y) {
        // whatever you want to do with the values
    }
});

You give it an area to listen to for touch or mouse events, and it gives you the x and y values with some momentum.

Impetus will register itself as an AMD module if it's available.

Constructor Options

Type Default Description
source HTMLElement|String document Element reference or query string for the target on which to listen for movement.
update (required) function(x, y) - This function will be called with the updated x and y values.
multiplier Number 1 The relationship between the input and output values.
friction Number 0.92 Rate at which values slow down after you let go.
initialValues [Number, Number] [0,ย 0] Array of initial x and y values.
boundX [Number, Number] - Array of low and high values. x-values will remain within these bounds.
boundY [Number, Number] - Array of low and high values. y-values will remain within these bounds.
bounce Boolean true Whether to stretch and rebound values when pulled outside the bounds.

Methods

Description
.pause() Disable movement processing.
.resume() Re-enable movement processing.
.setMultiplier( <number> ) Adjust the multiplier in flight.
.setValues( <number> , <number> ) Adjust the current x and y output values.
.setBoundX( <number[2]> ) Adjust the X bound
.setBoundY( <number[2]> ) Adjust the Y bound
.destroy() This will remove the previous event listeners. Returns null so you can use it to destroy your variable if you wish, i.e. instance = instance.destroy()

Browser Support

Chrome, Firefox, Safari, Opera, IE 9+, iOS, Android. Support for IE 8 can be achieved by adding a polyfill for addEventListener.

impetus's People

Contributors

chrisbateman avatar firasdib avatar htdt avatar rhysburnie avatar vsa avatar zearin 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  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

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

impetus's Issues

Multiply velocity on flick (fast swipe)

This behavior is how iOS native momentum scrolling works. Each swipe, that is faster than the last one, makes the animation faster.

For example:
Multiply the current velocity with dt, if the time threshold (touchend - touchstart) (in this case 100ms) is not reached.

Add an"snapToGrid"-option

It would nice to see a way, to get the "finish"-offset (where the "movement" will end). So we could calculate the closest offset (compared to our grid) and scroll to it (manullay?).

Do not cancel mousemove event

When impetus apply for a container which have some input children nodes, canceling mousemove event make the selecting text (mousedown and mousemove event happen) in the children nodes not broken.
I make a fix here #49
Related issue: dy/pan-zoom#16

Bounds rubber-banding

Hi there
Thanks for this very useful library.
I'm wondering if it would be possible to add a kind of negative inertia when bounds are defined thus the x/y props would be smoothly slowed down and bounced back to the bound value instead stopped immediately.

"main" property in bower.json incorrect.

The main property in the bower.json is incorrect. So tools like wiredep do not work correctly with it.

It needs to be "main": "dist/impetus.js".

You can work around this with bower overrides.

This is a great utility I really like it.

`Expecting a function in instanceof check, but got undefined` with .min file

I've just found that I get this only when I use gulp/browserify via npm in production mode. If I do a dev compile, it works fine!

Looks like it's failing on if(!(e instanceof t)) in the .min file, which is

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) in the regular one.

Any suggestions?

edit: It's not just the min file. I've taken the main JS now and am simply importing it. As soon as I add something as simple as this var myImpetus = new Impetus({ source: document.body, update: function(x, y) { // whatever you want to do with the values } });
everything breaks with Uncaught TypeError: Expecting a function in instanceof check, but got 1

I've got 40 other modules loading, and as soon as I remove Impetus, everything compiles!

unminified .js without bower?

would anyone be so kind to upload/send me an uniminified version of the impetus.js without all tth bower stuff? I want to modify impetus that it just fires the update function after touchend, not while, but I can't get it to run... :|

Functional tests

This will involve simulating gestures with custom mouse/touch move events, which should be interesting.

Dynamic update bounds

Hi Chris,

Is there a way to dynamically update bounds (if they are relative to an element for example) ?
Useful in react/angular context because content is dynamic.

If not, with this add, and Events #27, for me Impetus is close to perfect in his agnostic objectives.

Bounce Bug

Since I'm also using 2-finger pan/scaling, my use case needed the ability to pause/resume 1-finger panning, set initial and resume values, set initial and resume multiplier, set initial and resume X and Y bounds. And, not a useless feature to be seen. It's as if this package was tailor-made for my application. Great work!

Even the bounce feature seems like a nice touch, but I needed to disable it because I notice if the min and max bounds are the same (zero, in my case) it will infinitely bounce between values -1 and 1.

Remove scrollbars from swiping surface

I don't know if it's intended, but I ran into a problem with my Horizon library. I'm listening to several events and Impetus is triggering swipe event even when the mouse is over the scrollbar. I currently fixed this by automatically measuring the scrollbar width and then listening to mousedown/mouseup to know if we're manually scrolling or not.

Listeners added to document

Hi,
one question.
In addRuntimeEvents you add the move, up and cancel listeners to document.

I've two nested scrolling container, the internal is managed by your code.
I've an external function that prevents scrolling on certain condition to avoid scroll on an external container while the internal does some particular action.
Basically if the scroll happens in the internal container scroll is prevented.
The funcion is registered on the same DOM element you manage.
By doing this, you never receive touchmove events.
By registering move on the sourceEl you still have events managed by you and developers are able to prevent the event somewhere along the chain between the managed DOM element and document.
Thanks

Limit axes for performance?

First of all thanks for this little gem. It runs incredibly smooth and I was wondering if it makes sense to add a setting which limits the scrolling axes (x, y or both) to improve the performance even more when just one axis is needed.

Thank you!

Right click on an element causes impetus to "stick"

Right-clicking on an object causes impetus to start tracking the mouse movement and sending event updates. It does not stop tracking this until the user left clicks again.

To repro:

  • Right click on an impetus source
  • Click and release the left mouse button away from the context menu to make it disappear
  • Move the mouse

What I expect is that the source doesn't receive event updates

What I experience, however, is impetus continues to send tracking events until the user left clicks and releases the mouse button again.

Multitouch kills Impetus

I've got an app that has pinch to zoom enabled on a canvas element, and I noticed that my dragging of the canvas (controlled by Impetus), would just stop every now and then after pinch/zooming on my iPhone. No errors, just dead.

After some spelunking I've found that it's partially the onUp function receiving an event.id that is different then the pointer ID and never executing stopTracking(), never setting pointerActive to false, and never registering another onDown event.

I've attached 2 screens of an onMove followed immediately by an onUp which fails. Also, logged the pointerActive, event.id, and pointerID so you can see what's going on.

This doesn't happen all the time, it sometimes takes a few tries of finger pinch zoom mashing, but it happens 100% of the time...well you know what I mean ;)

screen shot 2016-01-08 at 11 03 28 pm

screen shot 2016-01-08 at 11 03 54 pm

setValues does not respect bounds

I've added scroll handler in my react component and allows me to beyond the bounds and never come back.

The expected thing is to come back

handleScroll = (event) => {
    const offsetX = this.state.offsetX + event.deltaX;
    const offsetY = this.state.offsetY + event.deltaY;
    this.impetus.setValues(offsetX, offsetY);
    this.setState({ offsetX, offsetY });
    event.preventDefault();
  }

feature request: manually trigger momentum

it would be really cool if the plugin provided a public method for manual momentum trigger, by providing two tracking points

also, i really miss a way to halt the ongoing "stepDecelAnim" programatically

How to judge whether the exercise has stopped

When I want to make a picker component, I want to adjust the displacement properly at the end of the movement. Is there any solution?

var max = this.$wrap.offsetHeight - this.itemHeight;
var offset = 0
new Impetus({
      source: this.el,
      boundY: [-max, 0],
      multiplier: 1,
      initialValues: [0, -this.current * this.itemHeight],
      update: (x, y) => {
        var dis = this.baseOffset() + y
        offset = this.getIndexByOffset(y)
        this.offset = dis
        this.$wrap.style.transform = `translate3d(0, ${dis}px, 0)`
      }
    })

Adding support for Typescript

I'm new to the Javascript/Typescript game. This library looked useful and was looking to incorporate it into a Typescript project, but, due to my inexperience with integrating modules that aren't Typescript and don't have a declaration file, I am having difficulty getting this integrated. I've tried to import this via

import { Impetus } from 'impetus'

When run, I'll get a Uncaught TypeError: impetus_1.Impetus is not a constructor. When looking at the dist code, I do see that it ends up creating a var Impetus = function Impetus(_ref).

So admittedly it isn't clear to me how that would translate to a class.

Are there any plans to add in Typescript support?

I'm considering just dropping this into a .ts file, since it is relatively small.

Destroy Impetus

Is it safe to instantiate a new Impetus object on the same dom element ? I need to reset min and max bound values after the viewport resize.

[Violation] Added non-passive event

To avoid unnecessary warning in console, this and all other touch event listeners can be modified to

window.addEventListener('touchstart', fn, hasPassive ? { passive: true } : false)

for hasPassive can a modernizr-like detector be used or has-passive-events package.

Implementing events

Hi Chris, and thanks for your tiny library that I expect since a really really long time.
To achieve the agnostic objectives, i think Impetus lacks Events.

  • onDown
  • onMove
  • onUp
  • onDecelStart
  • onDecelStop

with a ev argument passed in function.

what do you think?

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.