How to make an infinite scrolling image loop in css & javascript!
Analyze_
Posted on September 14, 2023
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>
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;
}
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);
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
Posted on September 14, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.