Goal
This is a follow-up question to this one.
I'm trying to create a parallax scrolling effect.
The parallax-container are implemented like so:
< div class="parallax slide-1" >< /div >
The parallax-effect successfully starts, when a container is scrolled into view and stops, when it has left the view.
Problem
Unfortunately when I place a parallax-container further down on a page the effect starts with the backgroundposition in the wrong place.
I understand why this problem shows up, but am not sure how to solve it.
What I need is basically this:
- Start the effect once a parallax-container is scrolled into view: works.
- Stop the effect once it has left the view: works.
- Only move the backgroundposition by the distance scrolled since it has entered the view. Not the distance scrolled relative to the top of the page.
For the parallax-container further down the page:
You can see the edges of the images. I'm trying to find a solution for that.
Thoughts
So far my attempts where based around the idea to get the distance of a parallax-container to the top of the page only once (dont update it with each scroll) and implement it in the calculations.
But I cant seem to get it to work properly. Am I missing something?
Some further clarification:
There can be multiple parallax-container on any page.
Each can have their own background image set. (in the css)
I dont know how many parallax-container will be on a page.
I dont know where they are placed.
Only those that are visible move.
Code
Only the relevant parts:
$(window).scroll(function(){ // Bind window scroll event
$( ".parallax" ).each(function() {
if( $( this ).is_on_screen() ) { // Check if element is visible on screen after DOM loaded
// ANIMATE PARALLAX EFFECT
// If Parallax Element is scrolled into view do...
// Variables
var speed = 2.5;
var calc = (-window.pageXOffset / speed) + "px " + (-window.pageYOffset / speed) + "px";
var container = $( this );
// Function
container.css({backgroundPosition: calc});
} else {
// ...otherwise do nothing
}
});
});