Monday 31 March 2014

Javascript: Parallax Scrolling Flickr - Tested working code


HTML file:

<!DOCTYPE html>
<html lang="en">

<head>
    <title>This is parallax scrolling</title>
       <meta charset="utf-8">
       <meta name="viewport" content="width=device-width, initial scale=1.0">
       <link rel="stylesheet" href="style.css"/>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
       <script type="text/javascript" src="js/parallax.js"></script>
      
</head>

<body>

    <div id="big-wrapper">
        <nav>
            <ul>
                <li><a href="#">Home</a></li>
                <li>
                    <a href="#">Programs</a>
                    <ul class="dropup">
                        <li><a href="#">SQL Server</a></li>
                        <li><a href="#">Windows Server</a></li>
                        <li><a href="#">.NET Programming</a></li>
                    </ul>
                </li>
                <li>
                    <a href="#">Services</a>
                    <ul class="dropup">
                        <li><a href="#">Visa processing</a></li>
                        <li><a href="#">University admission</a></li>
                        <li><a href="#">Company formation</a></li>
                    </ul>
                </li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>
    </div>

       <ul class="parallax">
              <li>
                     <div class="parallax-background flower"></div>
                     <div class="sampleContent">
                           <h1>Sample content</h1>
                           <h2>Hey there</h2>
                     </div>
              </li>
              <li>
                     <div class="parallax-background lens"></div>
                     <div class="sampleContent">
                           <h1>Sample content</h1>
                           <h2>Hey there</h2>
                     </div>
              </li>
              <li>
                     <div class="parallax-background beach"></div>
                     <div class="sampleContent">
                           <h1>Sample content</h1>
                           <h2>Hey there</h2>
                     </div>
              </li>
              <li>
                     <div class="parallax-background wolf"></div>
                     <div class="sampleContent">
                           <h1>Sample content</h1>
                           <h2>Hey there</h2>
                     </div>
              </li>
       </ul>

   
</body>
</html>

CSS file:

body
{
       margin:0;
       padding:0;
    width:100%;
}
ul
{
       margin:0;
       padding:0;
}
/*glass menu*/
#big-wrapper
{
       max-width:1000px;
    width:100%;
       margin:0px auto;
       text-align:left;
}
nav
{
       -webkit-box-sizing:border-box;
       width:1000px;
       position:fixed;
    z-index:99;
       margin:0 auto;
       padding:0px;
       top:0;
       text-shadow:1px 1px 1px black;
       border-top:1px solid rgba(0,0,0,0.3);
       background:rgba(0,0,0,0.4);
       -webkit-box-shadow:inset 0 -1px rgba(255,255,255,0.3);
       -webkit-box-shadow:inset 0 -10px rgba(255,255,255,0.25);
       -webkit-box-shadow:inset 0 -10px 20px rgba(255,255,255,0.25);
       -webkit-box-shadow:inset 0 15px -30px rgba(0,0,0,0.3);
      
      
      
      
}
nav li
{
       list-style:none;
       display:inline-block;
       padding:10px;
}
nav li a
{
       color:#aaaaaa;
       text-decoration:none;
      
}
nav li a:hover
{
       color:white;
}
/*programs menu drop box*/
nav li ul.dropup
{
       display:none;
}

nav li:hover ul.dropup
{
       display:block;
       position:absolute;
       margin:0 0 0 -15px;
       top:40px;
       border:1px solid #111111;
       border-top:none;
       background:rgba(0,0,0,0.5);
       -webkit-border-radius:0 0 5px 5px;
}
li:hover li{
       display:block;
       border-bottom:1px solid black;
      
}
/*parallax scrolling*/

.parallax li
{
       /*list is the window*/
       list-style:none;
       overflow:hidden;
       height:700px;
       position:relative;
}
.parallax-background
{
       /*list is the background of the window - we can earth what we see through window*/
       height:900px;
}

ul li .sampleContent
{
       text-align:center;
       position:absolute;
       top:200px;
       left:500px;
       color:white;
}

h1
{
       font-size:50px;
}



.flower
{
       background-image:url('Images/flower.jpg');
       background-size:cover;
       background-position:50% 50%;
}
.lens
{
       background-image:url('Images/lens.jpg');
       background-size:cover;
      
}
.beach
{
       background-image:url('Images/beach.jpg');
       background-size:cover;
       background-position:50% 70%;
}
.wolf
{
       background-image:url('Images/wolf.jpg');
       background-position:-70% 60%;
}


Javascript file:

$(window).load(function () {
    (function ($) {

        //reference to container
        var $container = $(".parallax");
        var $divs = $container.find("div.parallax-background");
        var thingBeingScrolled = document.body;//here body is being scrolled
        var liHeight = $divs.eq(0).closest("li").height();
        var diffHeight = $divs.eq(0).height() - liHeight;
        var len = $divs.length;

        var i, div, offset, scroll, top, transform;
        var offsets = [];
        $divs.each(function (i) {
            offsets[i] = $(this).offset();
        });

        //render as variable function
        var render = function () {
            top = thingBeingScrolled.scrollTop;
            for (i = 0; i < len; i++) {
                //get one div
                div = $divs[i];
                //console.log("hey");
                //calculate the offset of the DIV
                offset = top - offsets[i].top;
                //calculate the amount to scroll
                scroll = Math.round(((offset) / liHeight) * diffHeight);
                //apply the scroll amount
                transform = "translate3d(0px," + scroll + "px,0px)";
                div.style.webkitTransform = transform;
                div.style.MozTransform = transform;
                div.style.msTransform = transform;
                div.style.OTransform = transform;
                div.style.transform = transform;

            }
        };

        //function loop
        (function loop() {
            requestAnimationFrame(loop);
            render();
        })();

        //code for all browesers, requestAnimationFrame from Paul Irish
        (function () {
            var lastTime = 0;
            var vendors = ['webkit', 'moz'];
            for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
                window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
                window.cancelAnimationFrame =
                  window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
            }

            if (!window.requestAnimationFrame)
                window.requestAnimationFrame = function (callback, element) {
                    var currTime = new Date().getTime();
                    var timeToCall = Math.max(0, 16 - (currTime - lastTime));
                    var id = window.setTimeout(function () { callback(currTime + timeToCall); },
                      timeToCall);
                    lastTime = currTime + timeToCall;
                    return id;
                };

            if (!window.cancelAnimationFrame)
                window.cancelAnimationFrame = function (id) {
                    clearTimeout(id);
                };
        }());

    })(jQuery);
});




self executing function jquery vs javascript difference

In all cases you are doing an anonymous function. I think 1 is the same as 2. In the third case you are passing jQuery as an argument. This is done when you want to encapsulate jQuery within your function's scope.
For instance, in your application, jQuery var could be jQuery. But within your anonymous function you may want to use it as $.
(function ($) {
    //Here jQuery is $
    var Book = $(document.body).text();    

})(jQuery);

//Out of your function, you user jQuery as jQuery (in this example)
var Book = jQuery(document.body).text();




Theory:






requestAnimationFrame for Smart Animating


If you’ve never written code to animate inside the browser, you can stop reading :)

What is requestAnimationFrame?

In your animation work, you’ve used a timer loop to make changes every few milliseconds. Good for us: browser vendors have decided, “hey, why don’t we just give you an API for that, because we can probably optimize some things for you.” So it’s basic API for use with animation, whether that be DOM-based styling changes, canvas or WebGL.

Why should I use it?

The browser can optimize concurrent animations together into a single reflow and repaint cycle, leading to higher fidelity animation. For example, JS-based animations synchronized with CSS transitions or SVG SMIL. Plus, if you’re running the animation loop in a tab that’s not visible, the browser won’t keep it running, which means less CPU, GPU, and memory usage, leading to much longer battery life.

OMG I can brag about having a site with battery-friendly animations?

Yeah bro. Totes McGoats.

How should I use this?










1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();


// usage:
// instead of setInterval(render, 16) ....

(function animloop(){
  requestAnimFrame(animloop);
  render();
})();
// place the rAF *before* the render() to assure as close to
// 60fps with the setTimeout fallback.

Note: I am using ‘requestAnimFrame` here because since
the spec is still in flux, I don’t want to make a straight polyfill, yet.
2012.01.07: The spec has gotten some fixes and settled down. We’re also seeing ms and o implementations, so we’re ready for a polyfill now!

A robust polyfill

Opera engineer Erik Möller wrote about rAF and developed a polyfill that better handles browsers without native support. You can read about it, but basically his code will choose a delay of between 4ms and 16ms in order to more closely match 60fps. Here it is, in case you’d like to use it. Note it uses the standard method name. I have also fixed the cancel* method’s name, as it has changed in WebKit.









1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
(function() {
    var lastTime = 0;
    var vendors = ['webkit', 'moz'];
    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
        window.cancelAnimationFrame =
          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

I have this polyfill available as a gist as well.

Let’s see that in action


The requestAnimationFrame API










1
2
3
window.requestAnimationFrame(function(/* time */ time){
  // time ~= +new Date // the unix time
});

The callback is passed the current time as the first argument, as you’ll likely want that.
You’ll also notice the second parameter to requestAnimFrame: the element that visually bounds the entire animation. For canvas and WebGL, this will be the actual <canvas> element. For DOM stuff, you can leave it off or define it for a slightly more optimized experience.It’s since been removed from the spec (and WebKit’s implementation)

Is it ready?

Right now, the Webkit implementation (available in Nightly Safari and Chrome Dev Channel) and the Mozilla one (available in FF4) differ slightly. Mozilla’s has a bug which caps potential framerates at about 30fps.
Actually, “It’s currently capped at 1000/(16 + N) fps, where N is the number of ms it takes your callback to execute. If your callback takes 1000ms to execute, then it’s capped at under 1fps. If your callback takes 1ms to execute, you get about 60fps.” (thx, Boris) It’ll be fixed though, probably for the next release after FF4 ships. Also Chrome 10 doesn’t have the time parameter (added in m11), FF currently ignores the element argument.

We want your feedback!

If you do animation work, WebKit and Gecko hackers would love to hear if this meets your needs or if it could be improved any. Take a look at the draft requestAnimationFrame spec. It’s currently modeled like setTimeout; does a setInterval repeating style API make more sense? Does this API have downsides when animating multiple simultaneous elements? Does the element reference work for you? In general, does this solve the common cases of animation?

Resources for hackers

Thx @mrdoob for bringing this up today and spreading the good word.
2011.06.01: Joe Lambert took this idea and provided shims for both setTimeout and setInterval that leverage this. http://blog.joelambert.co.uk/2011/06/01/a-better-settimeoutsetinterval/
2011.10.13: Updated code sample and explained why the rAF call before render makes sense due to the timeout fallback.
2011.12.14: Updated code sample and text. Removed references to element argument, as it was removed from spec and webkit’s impl.
2012.01.01: Added polyfill from Erik Moller.
2012.01.05: Addressed polyfill fix from Tino Zijdel of DHTML Lemmings fame. :)
2013.03.06: No more `ms` or `o` prefixes neccessary. Removed.
2014.01.23: Someone asked if this polyfill is still neccessary. It is. Red and yellow-flagged entries still require the fallback and prefix normalization, respectively: 

No comments:

Post a Comment