Mobile tablet device orientation tracking Uses the event callback for deviceorientation window addEventListener style body min height 300px garden position relative width 200px height 200px border 5px solid CCC border radius 10px ball position absolute top 90px left 90px width 20px height 20px background green border radius 100 style div class garden div class ball div div pre class output pre script var ball document querySelector ball var garden document querySelector garden var output document querySelector output var maxX garden clientWidth ball clientWidth var maxY garden clientHeight ball clientHeight function handleOrientation event var x event beta In degree in the range 180 180 var y event gamma In degree in the range 90 90 output textContent beta x n output textContent gamma y n Because we don t want to have the device upside down We constrain the x value to the range 90 90 if x 90 x 90 if x 90 x 90 To make computation easier we shift the range of x and y to 0 180 x 90 y 90 10 is half the size of the ball It center the positioning point to the center of the ball ball style top maxY y 180 10 px ball style left maxX x 180 10 px window addEventListener deviceorientation handleOrientation console log ready script
ion handleOrientation event var x event beta In degree in the range 180 180 var y event gamma In degree in the range 90 90 output textContent beta x n output textContent gamma y n Because we don t want to have the device upside down We constrain the x value to the range 90 90 if x 90 x 90 if x 90 x 90 To make computation easier we shift the range of x and y to 0 180 x 90 y 90 10 is half the size of the ball It center the positioning point to the center of the ball ball style top maxY y 180 10 px ball style left maxX x 180 10 px window addEventListener deviceorientation handleOrientation console log ready script