Foo Fighters mobile device parallax


Recently, the Foo Fighters website has featured a countdown. We’ve yet to find out what it is counting down to. Whilst looking at the site on my iPhone, I noticed there is a clever parallax effect on the background image which is related to the position of the device. Naturally, as a curious front end developer, I dug a little deeper to see how they had achieved this.



window.addEventListener('deviceorientation', function(e) {
  var gamma, percent;
  gamma = e.gamma;
  percent = gamma / 90 * 50 + 50;
  return $('body').find('div').first().css({
    backgroundPosition: percent + "% 50%"
  });
});

http://lobby.foofighters.com/ff.js

Within ff.js, I discovered the above snippet of code. So what does it do? First of all it registers an event listener which monitors the device orientation and executes a function periodically returning data for any device orientation changes. The device can be thought of to have three axis – x, y, and z (as with 3 dimensional graphs). The x-axis spans from left to right of the screen, the y-axis goes from top to bottom of screen and the z-axis spans from the screen to the back of the device.

CoreMotionAxes

Returning to the code snippet above, the variable “gamma” stores the position of the device in relation to it being rotated around the y-axis from -90deg to +90deg. Using this value, a percentage is calculated to alter the position of the background image.

A clever way of creating a mobile device parallax effect!

Further reading:


Leave a Reply

Your email address will not be published. Required fields are marked *