Background image moving horizontally as scrolling down

Categories: Code

Tags: , , ,

Make a background image move horizontally as you scroll down with simple jQuery.

Parallax effects are a brilliant trick to use when you want to show off a beautiful image. It’s visually more engaging by giving the web page a depth. However, the parallax effects are usually vertical. How about a horizontal parallax effect that can move the image one side to another as we scroll down the page? I would like to share a simple technique that can do just that using a simple jQuery.

Firstly we will have 3 sections on the page, and locate the background images (one for a static image, another for a moving image) in the middle section to demonstrate the scrolling effect. Let’s build up the HTML markups. Really simple.

1
2
3
4
5
6
7
8
9
<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>

Next let’s give the HTML elements some styles and put the images in the middle section.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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://webmadewell.com/wp-content/uploads/2018/07/img-blog-background-move-scrolling-bg.png);
  background-size: cover;
  background-position: center;
}
.section .bg-move {
  position: absolute;
  top: 0;
  bottom: 0;
  right: auto;
  width: 100%;
  background-image: url(https://webmadewell.com/wp-content/uploads/2018/07/img-blog-background-move-scrolling-boat.png);
  background-size: cover;
  background-position: center;
}

The sample page should look like below. Very summer-like!

background sample

It looks nice, but too plane. Wouldn’t you agree? Let’s make it little bit more interesting by giving the boat a horizontal parallax effect. Simply add the jQuery code below.

1
2
3
4
5
6
7
8
9
10
$(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 });
  });
});

With the jQuery in place, now the boat is moving left to right as you scroll down making it little more fun. See it in action from the video below.

You can also see it in action at my CodePen page.