Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save addyosmani/1034311 to your computer and use it in GitHub Desktop.
Save addyosmani/1034311 to your computer and use it in GitHub Desktop.
CoffeeScript iPad Orientation and Motion detection
updateInputField = (el, value) ->
el.value = value
value += 10
el.setAttribute "style", "width:" + Math.round(value * 25, 10) + "px"
moveThing = (el, acc) ->
acc.x = Math.round(acc.x * 20)
acc.y = Math.round(acc.y * 20)
acc.z = Math.round(acc.z * 25)
attr = "-webkit-transform:translate3d(" + acc.x + "px," + acc.y + "px," + acc.z + "px);"
attr += "-webkit-transition-duration:0.1s"
el.setAttribute "style", attr
accTrackObj = (options) ->
acc = {}
accHistory = [ {}, {} ]
fake = ->
x: accHistory[0].x - accHistory[1].x
y: accHistory[0].y - accHistory[1].y
z: accHistory[0].z - accHistory[1].z
ondevicemotion = (e) ->
acc = e.accelerationIncludingGravity
accHistory[1] = accHistory[0]
accHistory[0] =
x: acc.x
y: acc.y
z: acc.z
options.ondevicemotion and options.ondevicemotion(acc, accHistory)
options.fake and options.fake(fake())
onorientationchange = ->
orientationDeg = window.orientation
orientationName = (if (orientationDeg == 90 or orientationDeg == -90) then "Landscape" else "Portrait")
options.onorientationchange and options.onorientationchange(orientationName, orientationDeg)
@start = ->
window.ondevicemotion = ondevicemotion
window.onorientationchange = onorientationchange
@stop = ->
window.ondevicemotion = null
window.onorientationchange = null
myAcc = new accTrackObj(
ondevicemotion: (acc) ->
updateInputField x, acc.x
updateInputField y, acc.y
updateInputField z, acc.z
moveThing thing2, acc
fake: (acc) ->
moveThing thing1, acc
)
window.onload = ->
x = document.getElementById("x")
y = document.getElementById("y")
z = document.getElementById("z")
thing1 = document.getElementById("thing1")
thing2 = document.getElementById("thing2")
<div class="thing" id="thing1">reacts to sudden movement</div>
<div class="thing" id="thing2">reacts to orientation</div>
<form onsubmit="return false;">
<button onclick="myAcc.start()">Start</button>
<button onclick="myAcc.stop()">Stop</button>
<br><label>x<input id="x"></label>
<br><label>y<input id="y"></label>
<br><label>z<input id="z"></label>
</form>
@addyosmani
Copy link
Author

Here's some prior work related to this:

iPad orientation detection
http://jsbin.com/emunu5/6/edit

Björn Söderqvist's motion detection for iPad in JS
http://jsbin.com/ogeha5/2/edit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment