5

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!

1 Answer 1

3

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 ;)

Sign up to request clarification or add additional context in comments.

5 Comments

Very nice! Since you're leaving it here, maybe you could publish it somewhere as well?
@Shomz with pleasure, can you recommend me where to publish?
jsfiddle.net/ZJ67y/1 is not working , can you give me alternative resource ?
OK @Arka ... I made a new jsfiddle jsfiddle.net/denoise/o1sbfqxb, I don't know what happened with the last one
Thank You very much. I always try to do anything in native. You excluded all library other than jquery. Now Im trying to do it except jquery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.