最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detecting shaking in html5 mobile - Stack Overflow

programmeradmin1浏览0评论

I'm building a web app in html5 at the moment that needs to be able to detect when the user shakes their phone and how fast they are shaking it. I've been browsing around but can't seem to find any examples of how I could implement this. I know html5 has an accelerometer that can detect the orientation of the phone, but how does it detect the speed at which the user is shaking it?

Also I'm testing this on my iPhone, although ideally I would like it to work on Android devices too. Thoughts? Examples would be great too. Thanks!

I'm building a web app in html5 at the moment that needs to be able to detect when the user shakes their phone and how fast they are shaking it. I've been browsing around but can't seem to find any examples of how I could implement this. I know html5 has an accelerometer that can detect the orientation of the phone, but how does it detect the speed at which the user is shaking it?

Also I'm testing this on my iPhone, although ideally I would like it to work on Android devices too. Thoughts? Examples would be great too. Thanks!

Share Improve this question asked Sep 8, 2012 at 20:23 Jessica StanleyJessica Stanley 3091 gold badge4 silver badges12 bronze badges 2
  • You can use this jQuery plugin. And you can also read this... html5rocks./en/tutorials/device/orientation The event, btw, must be supported by your mobile browser. – napolux Commented Sep 8, 2012 at 20:27
  • This was actually one of the only references I could find to it. I just couldn't get enough out of it to move on. Thanks, though! – Jessica Stanley Commented Sep 8, 2012 at 20:31
Add a ment  | 

1 Answer 1

Reset to default 2

shake.js looks to be a good library for this - it provides a custom 'shake' event and is supported on modern browsers. Here's an example setup from their documentation on how you could implement it:

<script src="shake.js"></script>
<script>
var myShakeEvent = new Shake({
    threshold: 15, // optional shake strength threshold
    timeout: 1000 // optional, determines the frequency of event generation
});

// Start listening to device motion
myShakeEvent.start(); 

// Register a shake event listener on window with your callback
window.addEventListener('shake', shakeEventDidOccur, false); 

//function to call when shake occurs
function shakeEventDidOccur () {

    //put your own code here etc.
    alert('shake!');
}
</script>

Note that this does not work in some browsers when in an insecure browsing context (eg. http://)

发布评论

评论列表(0)

  1. 暂无评论