Home » Tutorials » JavaScript » Introduction To Device Orientation With HTML5

Introduction To Device Orientation With HTML5

Introduction To Device Orientation With HTML5

  • Stumble it!
  • Share

Nowadays, almost every smartphones, laptops and mobile devices are shipping with accelerometers or other hardwares that used to detect orientation. Accelerometers often to be used to enhance the functionality and the value of the native application. Today, there are a lot of modern browsers support the device orientation on their latest releases, which means that, web developers can also adding the function of detecting the device orientation into their latest web project! The following tutorial is going to shows that how to handle the data of orientation and animate the image according to the data received.

The Basic Concept of Device Orientation

Let’s go through some basic concept, before we start the tutorial. The standard orientation is X-axis is horizontal, Y-axis is vertical and the Z-axis is points up as shown as below:
XYZ axis

Ok, you might ask that, so which position is the normal position without any accelerating mode (example: x:0, y:0, z:0)? For a mobile devices, such as smartphone, that’s probably put on the table with the screen facing up, and the the bottom of the phone is closest to you.

  • X-axis value is the amount of side to sde tilt.
  • Y-axis value is the amount of front to back tilt.
  • Z-axis value is the amount of vertical position.

Clear? Then, let’s begin our tutorial!

HTML Structure

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>onlywebpro.com</title>
</head>
<body>
  <h2>Device Orientation with HTML5 | onlywebpro.com</h2>
  <img src="test_img.png" id="imgLogo" class="logo">
</body>
</html>

First of all, we define our document type as HTML5, then follow with a header and a image. You can either create the image by yourself or use the following image:

onlywebpro logo
I use onlywebpro logo for this tutorial.

Ok. we already done the HTML structure, let’s move on to the JavaScript section to handle the data of device orientation.

JavaScript

When you are developing a web project, it is good practice to check for the browser compatibility before you start, to make sure your target user’s browser has the capability to support the feature of device orientation.

if (window.DeviceOrientationEvent) {
 console.log("DeviceOrientation is supported");
}

After you checking the browser compatibility, then the next step is add-in event listener to handle the event of device orientation.

if (window.DeviceOrientationEvent) {
  console.log("DeviceOrientation is supported");
  window.addEventListener('deviceorientation', function(eventData) {});
}

Ok, now we have added the event listener, it’s time to handle and process the data of orientation when users tilt their devices. The HTML5 DeviceOrientation event returns three pieces of data, which is gamma, alpha and beta.

  • gamma is the data of angle in degrees the device is tilted left-to-right, where right is positive.
  • alpha is the data of the direction the device is facing according to the compass.
  • beta is the data of the angle in degrees the device is tilted front-to-back, where front is positive.

so we need to create 3 variables to hold these data for us:

var LR = eventData.gamma;
var FB = eventData.beta;
var DIR = eventData.alpha;

once we received and store these 3 pieces of data into the variables that we created, then we have to pass it to another function called ‘deviceOrientationHandler’ to parse the data and animate the image for us according to the data received.

deviceOrientationHandler(LR, FB, DIR);

function deviceOrientationHandler(LR, FB, DIR) {
//for webkit browser
document.getElementById("imgLogo").style.webkitTransform = "rotate("+ LR +"deg) rotate3d(1,0,0, "+ (FB*-1)+"deg)";

//for HTML5 standard-compliance
document.getElementById("imgLogo").style.transform = "rotate("+ LR +"deg) rotate3d(1,0,0, "+ (FB*-1)+"deg)";
}

Final Code

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>onlywebpro.com</title>
</head>
<body>
  <h2>Device Orientation with HTML5 | onlywebpro.com</h2>
  <img src="test_img.png" id="imgLogo" class="logo">

<script type="text/javascript">
if (window.DeviceOrientationEvent) {
  console.log("DeviceOrientation is supported");
  window.addEventListener('deviceorientation', function(eventData) {
        var LR = eventData.gamma;
        var FB = eventData.beta;
        var DIR = eventData.alpha;
        deviceOrientationHandler(LR, FB, DIR);
	}, false);
} else {
	alert("Not supported on your device or browser.  Sorry.");
}

function deviceOrientationHandler(LR, FB, DIR) {
   //for webkit browser
   document.getElementById("imgLogo").style.webkitTransform = "rotate("+ LR +"deg) rotate3d(1,0,0, "+ (FB*-1)+"deg)";

   //for HTML5 standard-compliance
   document.getElementById("imgLogo").style.transform = "rotate("+ LR +"deg) rotate3d(1,0,0, "+ (FB*-1)+"deg)";
}
</script>

</body>
</html>

That’s it! Save your file and try it out on your device that has accelerometer enabled!

Sharing is Caring!

If you like this tutorial, please share it to your friends by using the social media icons at the top of this tutorial! Thanks :)

Other Popular HTML and JavaScript Tutorials


  • How To Create jQuery Password Strength Indicator in 10 Minutes!
  • Make A jQuery Sticky Header In 5 Minutes
  • Create Sequential Animations in jQuery

  • http://victorhh.com Victorhung92

    This is amazing. Thank you.. especially when today’s google logo got me head-scratching about how it was done. :)

  • Rafael Michels Motta

    Nice article.

  • Rafael Michels Motta

    Nice article.

    • http://www.onlywebpro.com onlyWebPro

      Thanks. :)

  • Anonymous

    Wud love to see a demo video.

  • Christian Ziebarth

    Still trying to figure this one out. I just uploaded the code along with an image and tested it and it didn’t do anything.

  • Christian Ziebarth

    Still trying to figure this one out. I just uploaded the code along with an image and tested it and it didn’t do anything.

    • http://www.onlywebpro.com onlyWebPro

      Hi, Christian,

      Would you mind to share out your code here?

  • Dalibor Sojic

    It would be nice if you place a link to Demo or Example page.

  • jjdewitt

    Excellent tutorial! This is working nicely. I’m trying to accomplish the following and thought I’d reach our for assistance. Any help would be greatly appreciated.

    - Instead of the current rotate and rotate 3d, I need to just move the image to the left only on the x-axis. My attempts at changing to translate (from rotate) haven’t been successful.

    - Also, I need two apply two unique transforms to two different images so that when the device orientation changes, both are affected differently. Is this possible? If so, how?

    Thanks!

    • http://www.onlywebpro.com onlyWebPro

      Hi Josh,
      Thank you for your comment. Please refer to the message on Facebook.

      Have a nice day! :)

  • Vinnie

    i tried it on my device (Lenovo Twist with Windows 8)
    and it says this function is not supported on my device

  • Marco

    and the link demo ?

Android, iOS Development Tutorials