Search code examples
javascriptjqueryhtmlcssparallax

Parallax scroll on background image while scrolling page


I'm stuck on a parallax issue and can't seem to find specifically what I want.

My page has a background image at the top. I have currently got background-position: fixed so it has a parallax effect however I need this image to scroll as the page scrolls? ...And now I'm stuck.

I believe this can be done with JavaScript and possibly background-position: scroll but I just don't know where to start.

In my basic fiddle you can see the parallax effect but I need the image to scroll as the page scrolls.

Thanks for any help.

.image {
  height: 100px;
  width: 100%;
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed;
  background-image: url('http://www.navipedia.net/images/a/a9/Example.jpg');
}
<section>
  <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."</p>
</section>

<div class="image"></div>

<section>
  <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta."</p>

  <br><br>
  
<p>"Sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est."</p>
</section>


Solution

  • This function will do the work for you. (change value of speed variable according to your choice)

    (function(){
    
      var parallax = document.querySelectorAll(".image"),
          speed = 0.5;
    
      window.onscroll = function(){
        [].slice.call(parallax).forEach(function(el,i){
    
          var windowYOffset = window.pageYOffset,
              elBackgrounPos = "50% " + (windowYOffset * speed) + "px";
    
          el.style.backgroundPosition = elBackgrounPos;
    
        });
      };
    
    })();
    

    See it in action: https://jsfiddle.net/ksugkmoh/