2
\$\begingroup\$

I'm working on website with a parallax effect. The jQuery code is working, but I wonder if there could be made any improvements made to the code. At the moment it works totally smooth in Firefox, but in other browsers it seems to be a little bit jumpy. Also, the effect is not working in IE 9.

(function($) {  

var $container = $(".parallax");
var $divs = $container.find("div.parallax-background");
var scrolledElement =  document.body;
var liHeight = $divs.eq(0).closest("li").height();
var diffHeight = $divs.eq(0).height() - liHeight;
var len = $divs.length;
var i, div, li, offset, scroll, top, transform;

var offsets = $divs.get().map(function(div,d){
    return $(div).offset();
    });



var render = function() {

    top = scrolledElement.scrollTop;
    for(i=0;i<len;i++) {

        //get the DOM object
        div=$divs[i];

        //our offset
        offset=top - offsets[i].top;

        //our transform string
        scroll= ~~(offset /liHeight*diffHeight);

        //our transform string 
        transform ='translate3d(0px, ' + scroll + 'px, 0px)';

        //apply
        div.style.webkitTransform = transform;
        div.style.MozTransform = transform;
        div.style.msTransform = transform;
        div.style.OTransform = transform;
        div.style.transform = transform;
        }
};
//Paul Irish http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
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);
        };
}());

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


})(jQuery);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.