orientationevents
, and add the platforms you want to target for this example.www
folder, open the index.html
file, and add div
with the #orientation
ID inside the main div
of the app beneath #deviceready
.<div class="app"> <h1>Apache Cordova</h1> <div id="deviceready"> ...... </div> <div id = "orientation"> </div> </div>
css
folder and define two new rules inside the index.css
file to give to div
and its content a border and a bigger font size.#orientation{ width: 230px; border: 1px solid rgb(10, 1, 1); } #orientation p{ font-size: 36px; font-weight: bold; text-align: center; }
js
folder, open the index.js
file, and define a new function to easily detect if the device can handle the orientationchange
and the deviceorientation
events.orientationSupported: function(){ try { return 'DeviceOrientationEvent' in window && window['DeviceOrientationEvent'] !== null; } catch (e) { return false; } }
deviceready
function, add two listeners if the device supports the orientationchange
and the deviceorientation
events.if(app.orientationSupported){ window.addEventListener('orientationchange', app.orientationChanged); window.addEventListener('deviceorientation', app.updateOrientation); }else{ navigator.notification.alert('Orientation not supported!', null, 'Attention!', 'OK'), }
orientationChanged
event handler and use it to print on screen the current device orientation.orientationChanged: function(){ var element = document.querySelector('#orientation'), element.innerHTML = '<p>' + window.orientation + '</p>'; }
deviceorientation
event and use the information provided by the device's sensor to change the 3D transformation of the orientation div
.updateOrientation: function(event){ var alpha = event.alpha, beta = event.beta, gamma = event.gamma; var element = document.querySelector('#orientation'), var rotation = 'rotateZ(' + alpha + 'deg) rotate(' + beta + 'deg) rotateY(' + gamma + 'deg)'; // For brevity the browser prefixes have been removed element.style.transform = rotation; }
3.134.118.95