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.
$('.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);
});
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!
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With