Coder Social home page Coder Social logo

alexgibson / shake.js Goto Github PK

View Code? Open in Web Editor NEW
1.5K 1.5K 281.0 319 KB

A custom 'shake' event plugin for mobile web browsers using device accelerometer.

Home Page: https://alexgibson.github.io/shake.js/

License: Other

HTML 25.93% JavaScript 74.07%

shake.js's People

Contributors

alexgibson avatar dandv avatar hayk avatar peterhry avatar sugarshin avatar tehsis avatar tong-zeng avatar xasos 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  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

shake.js's Issues

Simplify the API?

The current flow for detecting a shake looks more complicated than it needs to be:

var myShakeEvent = new Shake({ ... senstivity options ... });
window.addEventListener('shake', shakeEventDidOccur, false);
window.removeEventListener('shake', shakeEventDidOccur, false);
myShakeEvent.stop();

@leecrossley's cordova-plugin-shake-detection has a minimally simple API:

shake.startWatch(shakeEventDidOccur, /* ... sensitivity options ... */);
shake.stopWatch();

Could the API be simplified?

iphone

Do you know if there's a way with an iPhone to use this library but avoid the "undo typing" prompt coming up?

npm build error

error in ./node_modules/shake.js/shake.js

Module parse failed: Unexpected token (110:20)
You may need an appropriate loader to handle this file type.
|
| if (timeDifference > this.options.timeout) {

           window.dispatchEvent(this.event);

| this.lastTime = new Date();
| }

bower version 1.2.2 differs from github version 1.2.2

Hello!

I noticed that the code for the bower version of shake.js differs from the code on github. The big difference being that there is no e.detail.strength available in the function return.

Using 'bower install shake.js' it fetches the following code, even though bower.json clearly states that it's version 1.2.2 that's installed:

/*
 * Author: Alex Gibson
 * https://github.com/alexgibson/shake.js
 * License: MIT license
 */

(function(global, factory) {
    if (typeof define === 'function' && define.amd) {
        define(function() {
            return factory(global, global.document);
        });
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory(global, global.document);
    } else {
        global.Shake = factory(global, global.document);
    }
} (typeof window !== 'undefined' ? window : this, function (window, document) {

    'use strict';

    function Shake(options) {
        //feature detect
        this.hasDeviceMotion = 'ondevicemotion' in window;

        this.options = {
            threshold: 15, //default velocity threshold for shake to register
            timeout: 1000 //default interval between events
        };

        if (typeof options === 'object') {
            for (var i in options) {
                if (options.hasOwnProperty(i)) {
                    this.options[i] = options[i];
                }
            }
        }

        //use date to prevent multiple shakes firing
        this.lastTime = new Date();

        //accelerometer values
        this.lastX = null;
        this.lastY = null;
        this.lastZ = null;

        //create custom event
        if (typeof document.CustomEvent === 'function') {
            this.event = new document.CustomEvent('shake', {
                bubbles: true,
                cancelable: true
            });
        } else if (typeof document.createEvent === 'function') {
            this.event = document.createEvent('Event');
            this.event.initEvent('shake', true, true);
        } else {
            return false;
        }
    }

    //reset timer values
    Shake.prototype.reset = function () {
        this.lastTime = new Date();
        this.lastX = null;
        this.lastY = null;
        this.lastZ = null;
    };

    //start listening for devicemotion
    Shake.prototype.start = function () {
        this.reset();
        if (this.hasDeviceMotion) {
            window.addEventListener('devicemotion', this, false);
        }
    };

    //stop listening for devicemotion
    Shake.prototype.stop = function () {
        if (this.hasDeviceMotion) {
            window.removeEventListener('devicemotion', this, false);
        }
        this.reset();
    };

    //calculates if shake did occur
    Shake.prototype.devicemotion = function (e) {
        var current = e.accelerationIncludingGravity;
        var currentTime;
        var timeDifference;
        var deltaX = 0;
        var deltaY = 0;
        var deltaZ = 0;

        if ((this.lastX === null) && (this.lastY === null) && (this.lastZ === null)) {
            this.lastX = current.x;
            this.lastY = current.y;
            this.lastZ = current.z;
            return;
        }

        deltaX = Math.abs(this.lastX - current.x);
        deltaY = Math.abs(this.lastY - current.y);
        deltaZ = Math.abs(this.lastZ - current.z);

        if (((deltaX > this.options.threshold) && (deltaY > this.options.threshold)) || ((deltaX > this.options.threshold) && (deltaZ > this.options.threshold)) || ((deltaY > this.options.threshold) && (deltaZ > this.options.threshold))) {
            //calculate time in milliseconds since last shake registered
            currentTime = new Date();
            timeDifference = currentTime.getTime() - this.lastTime.getTime();

            if (timeDifference > this.options.timeout) {
                window.dispatchEvent(this.event);
                this.lastTime = new Date();
            }
        }

        this.lastX = current.x;
        this.lastY = current.y;
        this.lastZ = current.z;

    };

    //event handler
    Shake.prototype.handleEvent = function (e) {
        if (typeof (this[e.type]) === 'function') {
            return this[e.type](e);
        }
    };

    return Shake;
}));

Here the bower.json for reference:

{
  "name": "shake.js",
  "description": "A custom 'shake' event plugin for mobile web browsers using device accelerometer.",
  "version": "1.2.2",
  "author": {
    "name": "Alex Gibson",
    "email": "[email protected]"
  },
  "keywords": [
    "javascript",
    "shake",
    "gesture",
    "event"
  ],
  "main": "./shake.js",
  "repository": {
    "type": "git",
    "url": "https://github.com/alexgibson/shake.js.git"
  },
  "readme": "README.md",
  "licenses": [
    {
      "type": "MIT",
      "url": "http://opensource.org/licenses/MIT"
    }
  ],
  "dependencies": {},
  "homepage": "https://github.com/alexgibson/shake.js",
  "_release": "1.2.2",
  "_resolution": {
    "type": "version",
    "tag": "v1.2.2",
    "commit": "117b756c48557b01aedddd7442bde887d020bf3e"
  },
  "_source": "git://github.com/alexgibson/shake.js.git",
  "_target": "~1.2.2",
  "_originalSource": "shake.js",
  "_direct": true
}

Calibrate threshold

I noticed that threshold needs to be adjusted from device to device. There isn't a way to calibrate it?

One Time Shake event

Hi,
I am using this Library & found it very helpful for me,

Now my scenario is:
When One time shake occurs I want to show the images, I found there is no such function
in the Library to do this.
How can I do this via using this library

How we can determine that the shake is stopped now?

when shake starts, we can listen it using
window.addEventListener('shake', shakeEventDidOccur, false);

how we can determine that the shake is stopped now, and end user is not shaking the device ? Actually I have to show a different popup when device is shaking and when some one stop shaking the device, i have to show a different popup / alert. Can you guide me on it. Thanks

Create tags for the versions

If I want add "shake.js": "~1.1.0" in my bower.json, I get:

bower shake.js#~1.1.0 ENORESTARGET No tag found that was able to satisfy ~1.1.0

Please, create tags so we could get specific versions of your library from bower.

Shake event not triggered inside Android Webview

The shake event apparently isn't triggered inside Android Webview (Android 6.0), but it works fine inside iOS UIWebView (when I tried it on my iPhone 6).

Someone has suggested this is because the orientation in the Android manifest was set to 'fixed'.

Is there a work-around for this issue? How do I trigger a shake event inside Android Webview?

Thanks

Trigger event on shake stops ?

Hello,
Maybe it is a stupid question, but is there a simple mean to know when shake stops ?
It would really help in my current project.

Windows Mobile 10

FYI: Also works on Windows Mobile 10 (IE Edge)

You can update your doco to include it if you wish.

Awesome work.

Safari iOS event not firing

Appreciate this is an old repo but I can't find anything newer/better or any indicator this should/shouldn't work still.

On Safari on iOS, if I `alert('ondevicemotion' in window);`` it alerts "true" indicating the feature should be supported. However, even with the threshold set as low as 1, I still get no event on safari on iOS.

Any help much appreciated 🙏

Safari and iOS - cordova/phonegap support

Hello, sorry for this issue but I tried to find if there was already something open about this and it seems not.

I just wanted to ask if shake.js works on Safari and iOS using it along with cordova / PhoneGap, as on Android 4.1 works perfectly but on ios simulator does not seem to work, so i am just wondering if Safari and iOS in general are both fully supported by shake.js and if is there any tip to make it work on them in case is not supporting them.

Thank you!

Put new tag

In order to utilize the module loader, please have put new tag for bower.

Support adjustable threshold

I've tested this on two Android phones and it works on both in Chrome 31, but the sensitivity between the two devices "feels" pretty significant. One phone (Droid Razr Maxx) takes a pretty hard shake to trigger while the other phone (Nexus 4) triggers very easily. With the current code design there is no way to adjust the threshold, so I think it would be best to just expose this variable and let users adjust it as desired.

Shake is triggered when holding Ipad upright

I noticed that the shake event is triggered when turn my Ipad upright. It doesn't matter how slowly I turn it, whenever the pad is standing at a certain angle close to 90 degrees the event fires. This does not happen with the Iphone I'm testing on, though.

I tried switching from using accelerationIncludingGravity to just acceleration in your code, and that seemed to actually fix the Ipad issue, but it wouldn't work at all on Iphone.

What are the bounds of the threshold parameter?

The docs have a default threshold of 15. Is there a minimum / maximum number, eg: between 0 to 100?

Also, what are some mappings to values? Eg: 30 requires a "vigorous shake", and 10 is "any slow rotation"

change the event from 'devicemotion' to 'deviceorientation'

  1. when i ran this lib's code in Chrome, i found that :

[Deprecation] The devicemotion event is deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.

  1. when i modified the event from 'devicemotion' to 'deviceorientation', i also got the same warning!

DeviceMotionEventAndVibrate.html:81 [Deprecation] The deviceorientation event is deprecated on insecure origins, and support will be removed in the future. You should consider switching your application to a secure origin, such as HTTPS. See https://goo.gl/rStTGz for more details.

  1. Why you choose 'devicemotion' not 'deviceorientation' to wrote this lib? 3ks in advance.

Android 4.0.3

Your demo works on Asus Transformer Prime Android Browser running the latest firmware.

Multiple events triggered if instantiated multiple times

There are cases where multiple things on the screen may init a new Shake(). For example, if a CMS has various components which the editor adds, and more than one of them want to enable shake detection.

At the moment, this causes the shake-event to trigger for each initialized Shake(), so code outside "my" scope could cause the shake-event to occur multiple times.

I believe Shake() should somehow either

  1. check if it's already running, and return the running instance
  2. OR manage a list of registered Shakes and remove one
  3. OR change the concept (or offer the alternative) to use a callback - there seems to be a fork which does this; shake could just offer both: JonWallsten@3989b49

passing custom data/parameter to shake event

sometimes, we need feedback after a shake event, for example, if I can pass shake "strength" to the event, I can do lots of things according to the "strength".

I know we can pass a object named "detail" when create new CustomEvent

this.event = new CustomEvent('shake', {
                bubbles: true,
                cancelable: true,
                "detail":{"strength":0}
            });

but when we use document.createEvent:

this.event = document.createEvent('Event');
            this.event.initEvent('shake', true, true); 

I found that it works on my iphone (IOS7.1) and android(V4.4) by adding this line:

 this.event.detail={};

But it seems this is _not documented_ in any official specifications.
So, my question: is there a good solution to pass custom parameters for document.createEvent, thank you.

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.