Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can someone explain this code to me.!

My question is on regards to that code below: Can someone break this code down and explain step by step what is going on?

i know that XOffset And YOffset give you that windows(browser) (height & width).

Any reply would be thankful.

                                          --- Link ---

https://gameplayjdk.wordpress.com/2013/12/22/how-to-create-a-parallax-like-scrolling-effect-in-pure-javascript-22-12-2013/

function parallaxScroll () { var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft; var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop; var bgdiv = document.getElementById('parallax'); bgdiv.style.top = -(scrollTop * 0.2) + 'px'; }

window.onscroll = (function(e) { parallaxScroll(); });

Hi Edgar, I'll give this a shot...sorry in advance if I ramble or mention things you may already have an understanding of, but I'm not sure which parts of the code are causing you grief :)

I assume that the first line makes sense to you, simply defining the function named parallaxScroll()

Next, is a variable declaration for scrollLeft. This is the confusing part, and the area I assume is causing you the most grief. The declaration is using the ternary operator - the '?' combined with ':' which is basically a shorthand way of writing an 'if, else' statement. It works like this:

To the left of the '?' is a boolean expression to be evaluated. If it evaluates to 'True', then the code immediately following the '?' is executed up to the ':'. If the expression evaluates to 'False', then the code following the ':' is run, so you may look at it like this:

Expression to evaluate ? Run If True : Run If False

So, the second line of code is declaring and assigning a value to the variable named scrollLeft:

var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;

The expression being checked is (window.pageXOffset !== undefined) This simply checks to see if the X-offset already exists or is yet to be defined.With parallax themes, the user is always scrolling, and these values are always changing, so this would only be undefined when the page first loads, before the user scrolls down at all.

If window.pageXOffset already exists, then the expression evaluates to True and the existing value is used and assigned to scrollLeft. If window.pageXOffset is undefined, then the expression evaluates to False and the code (document.documentElement || document.body.parentNode || document.body).scrollLeft; is run. This is a long 'Or' statement - double pipes '||' is the Logical Or Operator - it looks in those various parts of the document to find a value for scrollLeft. When it finds one, that value is assigned to the variable.

Hopefully this is making sense at this point, if so then the third line of code is easy - it's just another ternary statement like the other: var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;

  • Expression to evaluate is: (window.pageYOffset !== undefined)
  • If it is true, then use the existing value: window.pageYOffset
  • If it is false, then look for the correct value: (document.documentElement || document.body.parentNode || document.body).scrollTop;

So now for the almost last of it...

var bgdiv = document.getElementById('parallax'); bgdiv.style.top = -(scrollTop * 0.2) + 'px'; } This is yet another variable assignment, no ternary goodness here though!

  • Select the document element with the ID 'parallax': document.getElementById('parallax');
  • Set that element's top positioning. The value will be -20% of the Y-offset stored in the scrollTop variable in pixels: bgdiv.style.top = -(scrollTop * 0.2) + 'px'; }
  • The plus sign in there is string concatenation, so if for example scrollTop = 100...then the top position assigned to this element will be "-20px"...which would put part of it off screen or otherwise out of sight and allow it to "float" in...or a similar effect.

The final part of this all is to call the parallax function: window.onscroll = (function(e) { parallaxScroll(); }); Now, this calls the function as the user scrolls through the page. In parallax-type sites, the "story" unfolds as the user scrolls downward and cool things happen.

In the tutorial you linked to above, all of this makes the elevator go down!

Anywho, hopefully all this typing conveyed the info you were looking for. If not, maybe somebody else can do better :P Or in ternary speak:

Question == answered ? High-five! : Somebody else jump on in here :)

1 Answer

Okay Edgar,

In a nutshell, this code makes an element with the id=#parallax scroll 20% slower than the rest of the document. I have gone through line by line and added comments that explain each step.

function parallaxScroll() {  // Create a new function that takes no artuments
    var scrollLeft = (window.pageXOffset !== undefined) ? window.pageXOffset : (document.documentElement || document.body.parentNode || document.body).scrollLeft;
// The pageXOffset and pageYOffset properties returns the pixels the current document has 
// been scrolled from the upper left corner of the window, horizontally and vertically. 
// These properties are read-only and they return a number. 
// The ? and : is a real snazzy way of writing an if/else statement so 
// scrollLeft is assigned under the following conditions: 
if (window.pageXOffset !== undefined) {  // if the user has scrolled across the page
  scrollLeft = window.pageXOffset        // set ScrollLeft to however many pixels he scrolled
} else {                                 // otherwise
  scrollLeft = (document.documentElement || document.body.parentNode || document.body).scrollLeft;
} //The Element.scrollLeft property gets or sets the number of pixels that an element's content is scrolled to the left.
// so IF window.pageXoffset is defined, assign it to the variable scrollLeft. If not, set it equal to however many pixels 
// left of the documentElement, parentNode, or body it is. Basically, this code says count the pixels to the left side 
// side of the window and call it "scrollLeft".

    var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;    
// This does the exact same thing but up and down, rather than left and right. 

    var bgdiv = document.getElementById('parallax');  
// this selects <div id= '#parallax'></div> and assigns it to the variable bgdiv 
// usually that would be expressed in jQuery as: 
    var bgdiv = $('#parallax'); // but whatever... you can do it in JS if you'd like. 

    bgdiv.style.top = -(scrollTop * 0.2) + 'px'; 
// You're using JS to change style values with the .style property
// The top property sets the top edge of an element to a unit above/below the top edge of its containing element.
// In this case measure the distance to the top of the window and scroll the div 20% slower.
}

window.onscroll = (function(e) {  // fire the function every time the user scrolls on the page
    parallaxScroll();
});

I noticed that the scrollLeft variable is defined and never utilized in this function. That is interesting. I've also never seen a horizontal parallax website I don't think...

Anyways, I hope this helps. A lot of this code can be condensed with jQuery. In my opinion that would make it easier to write and understand, but traditional JavaScript will work too.

Hope this helps!