Search code examples
javascriptdevice-orientation

Using Device Orientation on page load


I am trying to grab the alpha, beta and gamma coordinates through the deviceorientation event.

My code:

window.addEventListener('deviceorientation', function(event) {
  alert(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
});

JS Fiddle: https://jsfiddle.net/myL17nzt/

This works great to constantly grab the coordinates as the device moves, but I would like to just grab the coordinates on page load and not make it listen for movement. I tried changing window.addEventListener to window.onload, but that didn't do the trick.

Any ideas how I could accomplish this?

Thanks!


Solution

  • It would be better to have the listener remove itself.

    function deviceOrientation(event) {
      alert(event.alpha + ' : ' + event.beta + ' : ' + event.gamma);
      window.removeEventListener('deviceorientation', deviceOrientation);
    }
    window.addEventListener('deviceorientation', deviceOrientation);
    

    This way you don't have it being called for events that you don't care about. Some libraries have a function called once that removes the event listener after the first event occurence.