var $badges = $('.js-progress-badge') , $window = $(window) , windowOrientation = window.orientation , firstRun = true // window.orientation accounts for landscape orientations window.addEventListener('orientationchange', function() { windowOrientation = window.orientation console.log('orientation change') }, false); function tilt (rotation, $el) { if (rotation === null) return // Bump lower numbers so CSS animation doesn't flip between 0 and 360 if (rotation < 180) rotation = rotation + 360 var adjustedRotation = (rotation - windowOrientation).toFixed(1) console.log(rotation, windowOrientation, adjustedRotation) $el.css({transform: 'rotate(' + adjustedRotation + 'deg)'}) $el.parent().find('.js-badge-value').text(adjustedRotation) if (firstRun) { firstRun = false $el.css({ transition: 'transform 500ms ease-out' }) } } var throttled = _.throttle(tilt, 100) $badges.each(function () { var $gyroEl = $(this).find('.js-badge-gyro') if ($gyroEl.length && window.DeviceOrientationEvent) { setupGyro($gyroEl) $gyroEl.on('animationend', function() { resetGyro($gyroEl) }) } }) function setupGyro ($gyroEl) { $window.on('deviceorientation.gyro', function () { if (!event.alpha) { $window.off('deviceorientation.gyro') return } throttled(event.alpha, $gyroEl) }) } function resetGyro ($el) { $window.off('deviceorientation.gyro') $(this).css({ transform: '' }) console.log('Animation finished') }