I am having problems with background parallaxing. I made a small site for an event organized by some of my friends, and on this site I have a bunch of background images alternating between sections of content. I added some logic to offset these background images when scrolling to create a parallax effect.
It works quite well, and I did not notice any performance issues, but when using scrollwheel, parallaxing seems to lag behind WebKit browsers.
Here is the link to the site:
http://eventyrfestival.info/
The effect I tried to reproduce, at least for background images, is the one you see on the Spotify website:
https://www.spotify.com/
From looking at their source code, I seem to be doing more or less the same thing: I have a parallax function that calculates the background conversion based on the value of the scrollTopdocument, and this function is throttled to 16 ms and bound to the window scroll event. However, the background transformation on the Spotify website is instantaneous, and mine is visually behind the content. It is not “broken”, as it works well in Firefox / IE, and it works in WebKit browsers every time you scroll the scrollbar manually ... but it is really annoying.
Does anyone have any advice on what causes this jerk?
Here is the code for the parallax function (I use a prototype, so sorry for spam this):
parallaxBackground: function () {
var viewportTop = this.elements.$document.scrollTop();
var viewportBottom = viewportTop + this.elements.$window.height();
var scrollDelta = this.slideHeight + this.elements.$window.height();
$.each( this.backgroundSlides, function ( index, slide ) {
var slideTop = slide.$container.offset().top;
var slideBottom = slideTop + this.slideHeight;
if ( slideBottom < viewportTop || slideTop > viewportBottom )
return true;
var factor = 1 - ( slideBottom - viewportTop ) / scrollDelta;
this.transformBackground( slide.$image, this.slideLength * ( factor - 1 ) );
}.bind( this ) );
},
transformBackground: Modernizr.csstransforms ? function ( $backgroundElement, distance ) {
$backgroundElement.css( {
'-ms-transform': 'translate(0px, ' + distance + 'px)',
'-webkit-transform': 'translate(0px, ' + distance + 'px)',
'transform': 'translate(0px, ' + distance + 'px)'
} );
} : function ( $backgroundElement, distance ) {
$backgroundElement.css( 'top', distance );
}
And here is how it is bound (using Underscore for throttling):
this.elements.$window.on( 'scroll',
_.throttle( this.parallaxBackground.bind( this ), 16 ) );