javascripthtmldevice-orientationuideviceorientation

deviceorientation not working


Well I've got this little script:

<script>
window.addEventListener('deviceorientation', function(event) {
  var a = event.alpha;
  var b = event.beta;
  var g = event.gamma;
}, false);
</script>

<script>
setInterval('alert(""+g+"");', '1000');
</script>

Which should add the deviceorientation, attach it to the page, and alert every 1 second what the orientation currently is, the gamma.

It's not working, though? Nothing alerts! any tips... ideas...?

Edit: I get "Uncaught ReferenceError: g is not defined" in the console log... but it is defined!


Solution

  • The var statement sets the scope of a variable to the function it is in.

    You are trying to access a local variable in the global scope—where it doesn't exist.

    Additionally, you don't set the variable until a deviceorientation occurs, but you try to read it all the time.

    You would have to rewrite your code like this:

    <script>
    window.addEventListener('deviceorientation', function(event) {
    
      var a = event.alpha;
      var b = event.beta;
      var g = event.gamma;
    
      console.log( g.toString() ); // Better to use a non-blocking method like console.log to display results.
    
    }, false);
    </script>