Parallax Effect for Backgrounds

Written by on March 21st, 2007 in Ajax News.

Brett Taylor wanted to see if he could make a parallax effect in HTML+CSS+JS and make it cross-browser and came up with Parallax Backgrounds.

Scroll around and you will see that the text and content scrolls normally, but the different background layers scroll at different speed.

Maybe as useful as SKIP INTRO, but a nice experiment.

JAVASCRIPT:

  1.  
  2. function calcParallax(tileheight, speedratio, scrollposition) {
  3.   //    by Brett Taylor http://inner.geek.nz/
  4.   //    originally published at http://inner.geek.nz/javascript/parallax/
  5.   //    usable under terms of CC-BY 3.0 licence
  6.   //    http://creativecommons.org/licenses/by/3.0/
  7.   return ((tileheight) - (Math.floor(scrollposition / speedratio) % (tileheight+1)));
  8. }
  9.  
  10. window.onload = function() {
  11.  
  12.   window.onscroll = function() {
  13.     var posX = (document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : window.pageXOffset;
  14.     var posY = (document.documentElement.scrollTop) ? document.documentElement.scrollTop : window.pageYOffset;
  15.    
  16.     var ground = document.getElementById(’ground’);
  17.     var groundparallax = calcParallax(53, 8, posY);
  18.     ground.style.backgroundPosition = “0 ” + groundparallax + “px”;
  19.  
  20.     var clouds = document.getElementById(’clouds’);
  21.     var cloudsparallax = calcParallax(400, .5, posY);
  22.     clouds.style.backgroundPosition = “0 ” + cloudsparallax + “px”;
  23.   }
  24.  
  25.   document.getElementById(’javascriptcode’).onscroll = function() {
  26.     var posX = (this.scrollLeft) ? this.scrollLeft : this.pageXOffset;
  27.     var j = calcParallax(53, 16, posX);
  28.     console.log(’scroll js: ‘+ j);
  29.     document.getElementById(’javascriptcode’).style.backgroundPosition = j + “px 0″;
  30.   }
  31. }
  32.  

Parallax Background

Source: Ajaxian
Original Article: http://ajaxian.com/archives/parallax-effect-for-backgrounds

Leave a Reply

You must be logged in to post a comment.



Site Navigation