Simple Paralax Plugin

by kachibito

HTML

<div id="container">

    <div id="layer-1"><img src="http://placehold.it/400x150"></div>
    <div id="layer-2"><img src="http://placehold.it/300x150"></div>
    <div id="layer-3"><img src="http://placehold.it/200x150"></div>
    <div id="layer-4"><img src="http://placehold.it/100x150"></div>

</div>

CSS

html, body {
    height:450px;
    text-align:center;
}

#container {
    display:block;
    width:80%;
    height:450px;
    boder:1px solid #eee;
    margin:0 auto;
    position:relative;
    overflow:hidden;
}

#container div {
    width:600px;
    height:450px;
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-300px;
    margin-left:-300px;
    text-align:center;
    cursor:default;
    overflow:hidden;
}

#layer-1 {
    font:bold 20px Times,Serif;
    color:darkred;
}

#layer-2 {
    font:bold 48px Times,Serif;
    color:darkgreen;
}

#layer-3 {
    font:bold 120px Times,Serif;
    color:darkblue;
}

JavaScript

(function($) {
    $.fn.paralax = function(container, speed) {
        var $window = container,
            t = speed || 1,
            $object = this;
        return $window.on("mousemove resize", function(e) {
            $object.css({
                top: -(e.pageY - $window.height() / 2 - $window.offset().top) * t + $window.height() / 2,
                left: -(e.pageX - $window.width() / 2 - $window.offset().left) * t + $window.width() / 2
            });
        });
    };
})(jQuery);

$(function() {
    var area = $('#container');
    $('#layer-1').paralax(area, 1);
    $('#layer-2').paralax(area, 2);
    $('#layer-3').paralax(area, 3);
    $('#layer-4').paralax(area, 4);
});