background sample
Output: Codepen

Basic format HTML file:

<div class="section">
  Scroll down to see the effect
</div>
<div class="section bg-static">
  <div class="bg-move"></div>
</div>
<div class="section">
  The boat image is moving only when scrolling. 
</div>

Stylesheet Styling:

body {
  font-size: 1.5em;
  font-family: Arial, Helvetica, sans-serif;
}
.section {
  position: relative;
  max-width: 920px;
  min-height: 75vh;
  padding: 40px;
  margin: auto;
  background-color: #48c9b0;
  color: #ffffff;
}
.section.bg-static {
  background-color: #85c1e9;
  background-image: url("https://www.dropbox.com/s/v4u0mpzfplgjxaq/img-blog-background-move-scrolling-bg.png?raw=1");
  background-size: cover;
  background-position: center;
}
.section .bg-move {
  position: absolute;
  top: 0;
  bottom: 0;
  right: auto;
  width: 100%;
  background-image: url("https://www.dropbox.com/s/isdqow2394y3t35/img-blog-background-move-scrolling-boat.png?raw=1");
  background-size: cover;
  background-position: center;
}

Javascript Function:

$(window).on("load resize scroll", function() {
  $(".bg-static").each(function() {
    var windowTop = $(window).scrollTop();
    var elementTop = $(this).offset().top;
    var leftPosition = windowTop - elementTop;
      $(this)
        .find(".bg-move")
        .css({ left: leftPosition });
  });
});
background sample

You can also see it in action at CodePen page.

Leave a Reply

Your email address will not be published. Required fields are marked *