Reputation: 104
I'm trying to implement a parallax scrolling effect on a site (using this tutorial from Smashing Magazine). The parallax effect is working fine, but I need to get one of the sprites to stop scrolling when it reaches a certain point. By default, it continues scrolling until it is out of view.
The parallax effect works by animating the background position of the element. I am trying to get the dynamic background position using this code:
jQuery(function($) {
var elem = $("#heart-box");
var backgroundPos = $(elem).css("backgroundPosition").split(" ");
var xPos = backgroundPos[0],
yPos = backgroundPos[1];
$(window).scroll(function() {
console.log(yPos);
if ( yPos >= 210 ) {
$(elem).hide();
}
});
});
Instead, just the starting position is being returned, as defined in the CSS, and isn't changed in the console log when the page is scrolled.
When the page is scrolled, the background Y position is dynamically changed - the range of which is approximately -200px starting, through to 400px at its finish. When the background Y position reaches 210px, I want the element to have a fixed background position of 210px, not keep scrolling.
Any help would be great. Thanks.
Upvotes: 0
Views: 2324
Reputation: 3060
The initial value is returned because yPos
is set to the value of backgroundPosition outside of your scroll
callback. In Javascript only objects are passed by reference, so your backgroundPos
, yPos
and xPos
variables (which are primitive types - strings in this case) are not changed when the CSS property you retrieved them from changes; they have the value they were assigned initially since you never reassign them.
To make this work how you are expecting, you will need to retrieve the current background position inside the scroll
callback.
$(window).scroll(function() {
var backgroundPos = $(elem).css("backgroundPosition").split(" ");
var xPos = backgroundPos[0],
yPos = backgroundPos[1];
console.log(yPos);
if ( yPos >= 210 ) {
$(elem).hide();
}
});
To make this slightly more efficient, you could assign the result of $(elem)
to a variable outside of the scroll callback so that the selector is not called on every scroll event (more relevant if you were using a string as a selector):
var elem = $(elem);
...
elem.css("backgroundPosition").split(" ");
Upvotes: 3