Friday 4 April 2014

jQuery: Parallax scrolling Shoes - Plugin code


The parallax effects with jQuery

Article
Early this year, we can notice this new Nike website with an amazing scrolling effect. How it works? I’ll try explain that with my little code.

1Demo

EXPLANATION
schema
Note that there are visually 3 movements: The window scroll, the first shoes pair and the second one.
Shoes pair movements are independent, each one has a single coefficient for the scrolling movement

2HTML & CSS code

/* CSS */
.section {        width:540px; height:500px;
                  background:url(images/bg_freext.jpg) no-repeat #000; }
.section .inner { width:540px; height:500px;
                  background:url(images/fg_freext.png) no-repeat; }

<!-- html -->
<div class="section">
    <div class="inner">
        <!-- your content here -->
    </div>
</div>
So we need two div with background for the parent, and a transparent foreground for the child.

3JQuery code

// The plugin code
(function($){
    $.fn.parallax = function(options){
        var $$ = $(this);
        offset = $$.offset();
        var defaults = {
            "start": 0,
            "stop": offset.top + $$.height(),
            "coeff": 0.95
        };
        var opts = $.extend(defaults, options);
        return this.each(function(){
            $(window).bind('scroll', function() {
                windowTop = $(window).scrollTop();
                if((windowTop >= opts.start) && (windowTop <= opts.stop)) {
                    newCoord = windowTop * opts.coeff;
                    $$.css({
                        "background-position": "0 "+ newCoord + "px"
                    });
                }
            });
        });
    };
})(jQuery);

// call the plugin
$('.section').parallax({ "coeff":-0.65 });
$('.section .inner').parallax({ "coeff":1.15 });
To run the plugin, we need 3 parameters: the coefficient, when the plugin starts and when the plugin stops. After, we bind a function to the scrolling evenement. This function update the background-position-y by multiplying the value of the scroll by the coefficient.
Easy, right?
If you like (or not) this article, you can write a comment 26 or a tweet 505.

No comments:

Post a Comment