Quantcast
Viewing all articles
Browse latest Browse all 22

Detect / get iPad device orientation using HTML5

It is important for a game, web application of website to align itself or rearrage when the device orientation changes in iPad or iPhone devices. In this article we are going to discuss how to detect the change in device orientation using javascript and HTML5.

Using properties of the viewport meta tag is one of the way to access the change in device orientation. But we are going to handle using only javascript.

Image may be NSFW.
Clik here to view.

Image may be NSFW.
Clik here to view.

iPad Device orientation using HTML5 and javascript:

Code to handle device orientation.

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iPad Device orientation</title>
</head>
<body>
  <h2>iPad Device Orientation with HTML5</h2>
 Orientation :<span id="orientationLabel"></span>		

<script type="text/javascript">

if (window.DeviceMotionEvent==undefined) {

 	alert("Not supported on your device or browser.  Sorry.");

}
else
{
	window.ondevicemotion = function(event) {

		 var landscapeOrientation = window.innerWidth / window.innerHeight > 1;

		 if (landscapeOrientation)
		 {
		 	document.getElementById("orientationLabel").innerHTML = "Landscape";
		 }
		 else
		 {
		 	document.getElementById("orientationLabel").innerHTML = "Portrait";
		 }

	}
}

</script>
</body>
</html>

Explanation:

We first check whether the device supports “window.DeviceMotionEvent” or not.

if (window.DeviceMotionEvent==undefined) {

 	alert("Not supported on your device or browser.  Sorry.");

}
else
{

 	alert("Device Supports");

}

If the device supports “window.DeviceMotionEvent” then let us listen for the event.

window.ondevicemotion = function(event) {
}

Check with the orientation change with “window.innerWidth”

window.ondevicemotion = function(event) {

		 var landscapeOrientation = window.innerWidth / window.innerHeight > 1;

		 if (landscapeOrientation)
		 {
		 	document.getElementById("orientationLabel").innerHTML = "Landscape";
		 }
		 else
		 {
		 	document.getElementById("orientationLabel").innerHTML = "Portrait";
		 }

	}

Conclusion:

Simple javascript code to detect device orientation change in iPad. Comment if you have any doubt or suggestions.

Related posts:

  1. InnerHtml is not working in FireFox and Safari.
  2. javascript get url | get path of current page location
  3. div background image | using CSS Javascript
  4. Call jQuery function from javascript
  5. javascript to print HTML page

Viewing all articles
Browse latest Browse all 22

Trending Articles