Detecting device orientation with the javaScript API

- Andrés Cruz

En español
Detecting device orientation with the javaScript API

With this API we can obtain information about the orientation of a device such as a phone and/or tablet, specifically, this API provides us with an event with which we report data that indicates the orientation of the device or cell phone; we may use this information to rotate elements on our website; let's see.

The event addEventListener()

First thing's first; It is necessary to define the event that will detect the orientation of the device (deviceorientation):

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

The parameters are as follows:

  • The name of the event you want to "listen to"; in this case deviceorientation.
  • The name of the event handler; That is, that function that will periodically receive data about the orientation of the device.
  • Boolean that indicates whether we want (true) or not (false) to capture the event.

Obtaining data based on device orientation

The next step (after registering the handle called handleOrientation()) is to develop the handleOrientation(); which will periodically obtain data about the orientation of the device:

  • DeviceOrientationEvent.alpha: This value represents the rotation around the Z axis given in degrees in a range of 0 to 360.

Z axis rotation

logo html5
  • DeviceOrientationEvent.beta: This value represents the rotation around the X axis given in degrees in the range of -180 to 180; rotating the device from top to bottom as we see in the following figure.

Rotation on the X axis

  • DeviceOrientationEvent.gamma: This value represents the rotation around the Y axis given in degrees in the range of -90 to 90; moving the device from right to left (side to side).

     

Y axis rotation



  •  

The event object provides us with this data; that is to say; of the degrees of gamma, beta and alpha rotation.

function handleOrientation(event) {  var absolute = event.absolute;  var alpha    = event.alpha;  var beta     = event.beta;  var gamma    = event.gamma;  // resto del codigo, aqui se rotaran elementos u otra operacion }

Example: Using the DeviceOrientation event

Let's look at a small example where an image will be rotated and information about the orientation of the device will be displayed.

General considerations

  • rotateZ: To simulate rotation in the Y axis (with rotate we would obtain the same result).
  • rotateX: To simulate rotation in the X axis.
  • rotateY: To simulate rotation in the Z axis.

1. Check compatibility

We check browser compatibility.

if (!window.DeviceOrientationEvent)
	alert("Device Orientation no soportadas por tu navegador");

2. Listen to the Device Orientation event

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

3. Get DOM elements

  • We get the data.
  • We obtain the image to rotate according to the position of the device.
  • We obtain the headers where the degrees will be placed.
  • Finally, the checkboxes that allow you to block the X, Y and Z axes.
	var beta = event.beta; //X
	var gamma = event.gamma;//Y
	var alpha = event.alpha; //Z

	var img = document.querySelector('img');
	
	var alphaTag = document.getElementById('alpha');
	var betaTag = document.getElementById('beta');
	var gammaTag = document.getElementById('gamma');
	
	var blockAlpha = document.getElementById('blockAlpha');
	var blockBeta = document.getElementById('blockBeta');
	var blockGamma = document.getElementById('blockGamma');

4. Rotate the image

Finally we apply rotation to the image.

		// rotamos
		if (!blockBeta.checked) {
			img.style.webkitTransform = "rotateX(" + beta + "deg)";
			betaTag.innerHTML = beta;
		}
		if (!blockGamma.checked) {
			img.style.webkitTransform = "rotateZ(" + gamma + "deg)";
			gammaTag.innerHTML = gamma;
		}
		if (!blockAlpha.checked) {
			img.style.webkitTransform = "rotateY(" + alpha + "deg)";
			alphaTag.innerHTML = alpha;
		}

5. HTML

The HTML example:

<img src="/public/images/example/html/html5-logo.png"/>
<h1>Alpha: <span id="alpha"></span> <input id="blockAlpha" type="checkbox" /></h1>
<h1>Beta: <span id="beta"></span> <input id="blockBeta" type="checkbox" /></h1>
<h1>Gamma: <span id="gamma"></span> <input id="blockGamma" type="checkbox" /></h1>

Complete example

You can try the complete example by clicking here (remember to try the example from a mobile phone, tablet or any other device with a gyroscope).

Detecting screen orientation with CSS

We can also detect if the orientation is portrait or landscape with CSS; For that we use the media queries provided from CSS3:

@media all and (orientation: portrait) { ... }
@media all and (orientation: landscape) { ... }

Sources

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.