HTML5 Zone is brought to you in partnership with:

David Catuhe is a Microsoft HTML5 Evangelist based in Paris, France. He does much of his research on Windows 8, Kinect, and the various HTML5 standards and JS libraries. David is a DZone MVB and is not an employee of DZone and has posted 22 posts at DZone. You can read more from them at their website. View Full User Profile

How to Create a Cool Parallax Background for Windows 8 in Javascript

11.28.2012
| 3265 views |
  • submit to reddit

Parallax background is a really simple but extremely cool feature you can add to your application. You just need a div containing your background picture and a listview on top of it:

<div id="backgroundHolder">
</div>
<div class="blocksList" id="blocksList" data-win-control="WinJS.UI.ListView">
</div>

Then you have to use this CSS to display background picture larger than the current window:

#backgroundHolder {
    background-size: 120% 100%;
    height: 100%;
    width: 100%;

}

Next you have to add a cool picture as a background picture of your div.

Then with the little following function you can handle the scroll event of your list and move the position of your background:

 var attachParallax = function (listQuery) {
     var listViewDOM = document.querySelector(listQuery);
     var listView = listViewDOM.winControl;
     var backGroundHolder = document.querySelector("#backgroundHolder");
     document.querySelector(listQuery + " .win-viewport").addEventListener("scroll", function (e) {
         setImmediate(function() {
             backGroundHolder.style["background-position-x"] = 
              -((scrollViewer.scrollLeft / scrollViewer.scrollWidth) * 
                 listViewDOM.clientWidth * 0.2) + "px";
         });
     });
 };

Considering that the background image is 20% larger than the main window, the idea of this function is to get a scaling ratio based on the scroll bar position. The result is used to move the left position of the background (from 0 to 20% of the window’s width).

But we have an issue with the smoothness of the translation. To resolve this problem, you can use the wonderful power of CSS3 transitions Sourire

#backgroundHolder {
    background-size: 120% 100%;
    height: 100%;
    width: 100%;
    transition-property: background-position-x;
    transition-timing-function: ease;
    transition-duration: 0.8s;
}

So thanks to these CSS rules, the position of the background will change smoothly instead of jumping from a position to the next one!

Obviously the next version of UrzaGatherer will include this feature!

At the begining:

image

Then after you scroll a bit, you can see that the background (1) only moved a few pixels where the foreground (2) moved almost the entire screen:

image

Published at DZone with permission of David Catuhe, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)