Platinum Partner
css,html5,javascript,tips and tricks,.net & windows,windows 8,parallax background

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

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 {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}