In this tutorial I will show how to detect phone shake with just few lines of JavaScript code. We will be using shake.js library to detect it. This library uses Device Orientation API to function.
Example
Here is just few lines of code to detect phone shake
View Demo
<script type="text/javascript" src="https://cdn.rawgit.com/alexgibson/shake.js/master/shake.js"></script>
<script>
//listen to shake event
var shakeEvent = new Shake({threshold: 15});
shakeEvent.start();
window.addEventListener('shake', function(){
alert("Shaked");
}, false);
//stop listening
function stopShake(){
shakeEvent.stop();
}
//check if shake is supported or not.
if(!("ondevicemotion" in window)){alert("Not Supported");}
</script>
<script>
//listen to shake event
var shakeEvent = new Shake({threshold: 15});
shakeEvent.start();
window.addEventListener('shake', function(){
alert("Shaked");
}, false);
//stop listening
function stopShake(){
shakeEvent.stop();
}
//check if shake is supported or not.
if(!("ondevicemotion" in window)){alert("Not Supported");}
</script>
You can also use this code snippet on Phonegap or Intel XDK APP.
Leave a Reply