Question

I am trying to make a simple Parallax effect for my background images, everything seems to be working, but the background image jumps on first scroll and then it works! I can't seem to figure out why it keep on jumping, Live Preview: http://loai.directory/gallery

HTML:

<div class="topSection parallax">
         <div class="content">
         </div>
      </div>

CSS:

#page {
   background-color: #3F8AE4;
   padding-top: 80px;
   text-align: left;
}

   /*Wrappers*/
   .wrapper {
      background-color: #ffffff;
   }

   .wrapper.A {
      background-color: #EDEDED;
      border-top: 1px solid rgba(0,0,0,0.1);
      border-bottom: 1px solid rgba(0,0,0,0.1);
   }

      /*Content Container*/
      .content {
         width: 1024px;
         padding: 50px 20px;
         margin: auto;
         overflow: hidden;
         position: relative;
      }

   /*Top Section*/
   .topSection {
      color: #fff;
      background-color: #3F8AE4;
      border-bottom: 1px solid rgba(0,0,0,0.1);
      padding: 10px 0;
   }

.parallax {
   background: url(../images/backgruond.jpg) no-repeat center center fixed;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
   background-size: cover;
   padding: 150px 0;
}

JS:

// Y axis scroll speed
var velocity = 0.5;

function update(){ 
    var pos = $(window).scrollTop(); 
    $('.topSection').each(function() { 
        var $element = $(this);
        // subtract some from the height b/c of the padding
        var height = $element.height()-0;
        $(this).css('background-position', '50%' + Math.round((height - pos) * velocity) + 'px'); 
    }); 
};

$(window).bind('scroll', update);
Was it helpful?

Solution

Your background-position is set to center center by your default CSS, but then as soon as you start scrolling, it is set to 50% 50px... So the jump comes from the vertical position changing from centered to calculated.

You can approach this from two ways, either just set your initial css to be:

background: url(../images/backgruond.jpg) no-repeat 50% 50px fixed;

because you know that that's the position it gets set to as you start to scroll,

Or, just call your update() function on pageload in addition to on scroll, therefore allowing the position to be calculated immediately.

For example:

$(window).bind('scroll', update);
update();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top