DEV Community


Posted on

How to make an infinite scrolling image loop in css & javascript!

In this tutorial, I am going to teach you how to create an infinite horizontal scrolling image in css & javascript!

Step #1: HTML
You are going to need to create a <div> with the ID and class of "landscape," although you can name it whatever you would like.


<div class="landscape" id="landscape"></div>
Enter fullscreen mode Exit fullscreen mode

Step #2: Finding the right image
You are going to need to find an image that loops when it is next to itself horizontally. This might be hard to find. If you can't find one you like, you can always just make your own in something such as Photoshop.

For mine I used a cartoon cloud image (See Here).

Step #3: CSS
For this you are going to fix the div to the page and make sure it fills the whole page. You also need to do things, like set the z-index to -1 so that it is positioned behind any other elements.


  background-size:1200px 650px;
Enter fullscreen mode Exit fullscreen mode

Step #4: JavaScript
Last but not least, to make the movement of the background, you will need to use JavaScript. Essentially all it is, is a repeating loop that changes the background-image's background-position by one using a variable. This variable increases by one integer each time the function is called, creating the movement effect.


var x = 1;
var bgImage = document.getElementById('landscape');

function move(){
  x++; = x + "px";

setInterval(move, 50);
Enter fullscreen mode Exit fullscreen mode

If you want, you can change the interval time to change the speed of the background image.

Thanks for reading, I hope it helped!

  • Quinn

Top comments (0)