DEV Community

Analyze_
Analyze_

Posted on

7 1 1 1 2

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.

Code:

<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.

Code:

.landscape{
  position:fixed;
  top:0px;
  left:0px;
  background:url('..path/to/image.png');
  width:100vw;
  height:100vh;
  background-size:1200px 650px;
  background-position:0px;
  z-index:-1;
}
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.

Code:

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

function move(){
  x++;
  bgImage.style.backgroundPositionX = 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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more