I'm trying to create a parallax scrolling effect.
The parallax-container are implemented like so:
< div class="parallax slide-1" >
< /div >
I need the parallax effect to start, when its container is scrolled into view.
The jQuery works fine so far.
But: Since I can have multiple parallax-container on one page (e.g. one at the top + one at the bottom) I need them to be treated independently by jQuery.
At the moment the effect is...
So not quite the solution yet.
I think it should work with jQuerys .each(), but I couldn't really get it to work so far.
I think I'm getting confused with the nested functions somewhere, when I try to implement it.
Here's my current code:
$(document).ready(function(){
$.fn.is_on_screen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
$(window).scroll(function(){ // Bind window scroll event
if( $('.parallax').length > 0 ) { // Check if target element exists in DOM
if( $('.parallax').is_on_screen() ) { // Check if target 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 = $(".parallax");
// Function
container.css({backgroundPosition: calc});
} else {
// ...otherwise do nothing
}
}
});
})
Assuming the scrolling you want to do is identical (using the same parallax methods,etc), you could just use the .each on the class. Example:
$(window).scroll(function(){ // Bind window scroll event
$( ".parallax" ).each(function() {
if( $( this ).is_on_screen() ) { // Check if target element is visible on screen after DOM loaded
// ANIMATE PARALLAX EFFECT
// If Parallax Element is scrolled into view do...
// remember to replace ('.paralax') with (this)
// 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
}
});
});
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