// Check for device orientation support
if (window.DeviceOrientationEvent) {
var
// The Orientation when we last checked for tilt
lastOrientation,
// The current Orientation
currentOrientation,
// How often we check for a tilt
tiltTime = 100,
// How much we must rotate to tilt
tiltThreshold = 100,
// The div that shows the rotation
odiv = document.getElementById("orienter"),
// The interval that updates the tilt
tiltInterval = setInterval(tiltCheck, tiltTime);
// Class to hold orientation information
function Orientation(x, y, z) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
}
// Member to get difference between two Orientations
Orientation.prototype.diff = function (o) {
return new Orientation(
this.x - o.x,
this.y - o.y,
this.z - o.z);
};
// Member to find magnitude of Orientation
Orientation.prototype.mag = function () {
return Math.sqrt(
(this.x * this.x) + (this.y * this.y) + (this.z * this.z));
};
// Function to handle when titled
function tiltHandler() {
console.log("tilt");
// Visualize the tilt
odiv.className = "tilt";
// Reset after a time
setTimeout(function () {
odiv.className = "";
}, 2000);
}
// The function that checks for tilts
function tiltCheck() {
// If we have an orientation to compare to
if (lastOrientation) {
// Get how much we rotated
var mag = currentOrientation.diff(lastOrientation).mag();
// If it's more than the threshold
if (mag > tiltThreshold) {
// We tilted
tiltHandler();
}
}
// Always update the last orientation
lastOrientation = currentOrientation;
}
// Add an orientation listener
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.