HTML5 Device Orientation Demo

2015-07-29 00:00:00 by Mike

Want to build an interactive parallax like the iOS app icons that shift perspective?
It's easier than you might think.

Thanks to the HTML5 device orientation API you can build it.

Here's the demo (click here to see it in a full window):

Here's the JavaScript:

window.addEventListener("load", function() {

	var eleOrientationBeta = document.getElementById("orientationBeta");
	var eleOrientationGamma = document.getElementById("orientationGamma");
	var eleDevice = document.getElementById("device");
	eleDevice.style.top = "75px";
	eleDevice.style.left = "75px";

	function processOrientation(event) {
		var beta = event.beta;
		var gamma  = event.gamma;

		eleOrientationBeta.innerHTML = beta;
		eleOrientationGamma.innerHTML = gamma;
		intTop = (eleDevice.style.top).replace("px","");
		intLeft = (eleDevice.style.left).replace("px","");
		eleDevice.style.top = (80 + beta) + "px";
		eleDevice.style.left = (100 + gamma) + "px";
	};

	window.addEventListener("deviceorientation", processOrientation, true);

});

Here's the CSS and HTML:

<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<link rel="shortcut icon" href="" />
	<title>Device Orientation demo - pixelOneZero.com</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
	body {
		font-family: Helvetica, Arial;
		font-weight: 100;
		color: #333;
		font-size: .75em;
		padding:1em;
	}
	.column-40 {
		float:left;
		width:47%;
		margin-right:.5em;
	}
	.column-100 {
		width:100%;
		margin:2em 0 0 0;
		clear:left;
		display:inline-block;
	}
	.output {
		padding: 1em;
		margin: 0.5em 0;
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
		background: #def;
		border: 1px solid #aaa;
	}
	#diagram-container {
		position: relative;
		height: 255px;
		width: 255px;
	}
	#diagram-container.output {
		padding:0;
	}
	#device {
		position:absolute;
		height:50px;
		width:50px;
		background:#555;
	}
	</style>
</head>
<body>

<div class="column-40">
	Beta:
	<div id="orientationBeta" class="output">
	</div>
</div>
<div class="column-40">
	Gamma:
	<div id="orientationGamma" class="output">
	</div>
</div>

<div class="column-100">
	Beta &amp; Gamma Illustrated:
	<div id="diagram-container" class="output">
		<div id="device">
			
		</div>
	</div>
</div>

</body>
</html>