I want to apply a parallax effect to a background image which can be positioned everywhere in a page inside a DIV.
I try to find the "perfect" equation in order to see the background image entirely (from top to bottom) when document is scrolled, while having always image filling fully the DIV.
Finally I just want a parallax image in the middle of a page that always work whatever the image height and window height.
Here my script (it works but my calculations don't take care completely of the window height and image height ...)
$("#inner-container").on("scroll", function() {
var scrollTop = $(this).scrollTop();
var windowHeight = $(window).height();
$('.parallax-container').each(function() {
var parallaxDivPosition = $(this).position().top;
var parallaxHeight = $(this).height();
var scrollPosition = scrollTop + windowHeight;
if (parallaxDivPosition <= windowHeight && parallaxDivPosition+parallaxHeight >= 0) {
var parallaxFactor = parallaxHeight/windowHeight;
var parallaxShift = parallaxHeight*parallaxFactor;
var parallaxImgPos = parallaxDivPosition-windowHeight;
var imagePosition = Math.round(parallaxImgPos-parallaxShift)*0.2;
$(this).children().css('-webkit-transform', 'translate3d(0px, '+imagePosition+'px, 0px)');
}
})
})
here a fiddle: http://fiddle.jshell.net/uccE4/12/