I've created this function to parallax scroll the passed element's background image.
When the view-port is less than 600px in height (600px is the height of the rainbow image) in the example below, the rainbow background does not properly cover the grey element behind it (it should be completely covered at all times, but is scrolling too fast)
I can't seem to figure out the extra terms I need in yB. Can you please help point me in the right direction for an equation to dynamically offset the background?
jsfiddle to recreate: http://jsfiddle.net/3htbj/
/**
Get the height of the passed element's background image.
@param {element} element - An element.
@returns {int} The height of the background.
***************************************************************************/
function getBackgroundHeight(element){
return 600;
}
/**
Parallax scroll the passed element's background relative to the element.
@param {element} element - An element.
***************************************************************************/
function parallaxScrollElement(element){
var hV=window.innerHeight;
var hE=element.clientHeight;
var hB=getBackgroundHeight(element);
var yV=window.pageYOffset; //Relative to document.
var yE=element.getBoundingClientRect().top; //Relative to view-port.
var yB=((hB-hE)*yE)/(hE-hV); //Relative to element.
element.style.backgroundPositionY=yB+"px";
}
/**
Parallax scroll all elements with CSS class 'parallax'. This function
should be called onScroll.
***************************************************************************/
function parallaxScroll(){
var parallaxScrollElements=document.getElementsByClassName("parallax");
for(var i=0;i<parallaxScrollElements.length;i++)
parallaxScrollElement(parallaxScrollElements[i]);
};
window.onscroll=function(){
parallaxScroll();
}
window.onresize=function(){
parallaxScroll();
}
If you are looking to parallax scroll along with the page's content, try:
var yB=((yE)/(hV))*(hE-hB);