JSFiddle - React, Tailwind, and code Playground
by HYEONGJINKIM
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="initial-scale=1.0, width=device-width, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>Shake.js</title>
<style type="text/css">
body {
background: #E9E9E9;
color: #333;
font: 1em/1.3em "Helvetica Neue", Helvetica, Arial, Verdana, sans-serif; /* 16px / 21px */
text-shadow: rgba(255,255,255,0.8) 0 1px 0;
text-align: center;
}
</style>
<script type="text/javascript" src="shake.js"></script>
</head>
<body>
<h1>Shake to Undo</h1>
<h2>for your mobile web app</h2>
<p>Shake your iPhone/iPad to see a custom action.</p>
<p>Works on iOS +4.2.1, Android 4.0.3 (default browser), Opera Mobile (Android), BlackBerry PlayBook 2.0</p>
<p><a href="http://dev.w3.org/geo/api/spec-source-orientation">W3C DeviceOrientation Event Specification</a></p>
<script type="text/javascript">
window.onload = function() {
window.addEventListener('shake', shakeEventDidOccur, false);
//define a custom method to fire when shake occurs.
function shakeEventDidOccur () {
alert("aa");
}
};
</script>
</body>
</html>
JavaScript
/*
*
* Find more about this plugin by visiting
* http://alxgbsn.co.uk/
*
* Copyright (c) 2010-2012 Alex Gibson
* Released under MIT license
*
*/
(function (window, document) {
function Shake() {
//feature detect
this.hasDeviceMotion = 'ondevicemotion' in window;
//default velocity threshold for shake to register
this.threshold = 15;
//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
this.event = document.createEvent('Event');
this.event.initEvent('shake', true, true);
}
//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,
currentTime,
timeDifference,
deltaX = 0,
deltaY = 0,
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...