Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Parallax Effect Algorithm

I'm developing a very simple parallax effect algorithm for a webpage. I don't want to use plugins or large libraries for this effect, since they are too bulky for my purposes. I just want a simple function that works with every background image on a div (or section) without giving an extra html data, like a 'speed' value.

Here is the whole function:

$('.parallax').each(function() {
    var thisObj = $(this);
    var tH = $(this).outerHeight();
    var tY = $(this).position().top;
    var wH = $(window).height();

    function bgParallax() {
        var s = $(window).scrollTop();          
        var offset = 1-((s+wH-tY)/(wH+tH)); /* parallax algorithm */

        thisObj.css('background-position','0 '+(offset*100)+'%');
    }

    bgParallax(); /* initial position */    
    $(window).scroll(bgParallax); 
});

Here is the result:

http://jsfiddle.net/ZL65K/

as you can see, the parallax algorithm works as follows generating a number between 0 and 1 when the .parallax object is on the viewport:

1-(scroll position + viewport height - object height) / (viewport height + object height)

then, this number serves as a multiplicator for showing the background image from 100% to 0% on the y coordinate.

Can you help me improve this algorithm? Now the functions works OK, but not perfect, specially on divs on the top of the webpage. I want to show the background image as much as possible during the scrolling, ideally all of its height.

thanks!

like image 618
denoise Avatar asked Oct 21 '22 04:10

denoise


1 Answers

OK.. I finally managed to write a satisfactory algorithm.

I added two multipliers, one for the hidden elements further bottom on the page and a second one for the elements already visible on the top of the page:

if (wH<tY) 
    var offset = 1-((s+wH-tY)/(tY+tH));
else
    var offset = 1-(s/(tY+tH));

Here you can see it in action:

http://jsfiddle.net/denoise/o1sbfqxb/

I hope someone can use it as a simple standard parallax function on the future ;)

like image 141
denoise Avatar answered Oct 22 '22 23:10

denoise