I'm currently working on a site where the stage/hero has a set of divs with looping background images (images of text), and I'm using jQuery to animate their positioning to give the appearance of an "ocean" of images moving across the screen.
var position = 0;
setInterval(function () {
position -= 1;
$(".sub-image-1").css({ "background-position":+ position +"px 0px" })
}, 20 );
setInterval(function () {
position -= 1;
$(".sub-image-2").css({ "background-position":+ position +"px 0px" })
}, 140 );
setInterval(function () {
position -= 1;
$(".sub-image-3").css({ "background-position":+ position +"px 0px" })
}, 200 );
.stage-image {
width:100vh;
height:30vh;
}
.stage-sub-image {
position:absolute; top:0;
width:100%;
height:100%;
background-repeat:repeat-x;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="stage-image">
<div class="stage-sub-image sub-image-1" style="background:url(https://upload.wikimedia.org/wikipedia/commons/c/ca/Triple-Spiral-4turns_green_transparent.png)"></div>
<div class="stage-sub-image sub-image-2" style="background:url(https://upload.wikimedia.org/wikipedia/commons/b/be/Blender3D_Lisc_lipy-Transparent.png)"></div>
<div class="stage-sub-image sub-image-3" style="background:url(https://cdn0.iconfinder.com/data/icons/ball/256/transparent.png)"></div>
</div>
I'm curious if there is a better approach to this solution that is less browser intensive. I feel setInterval
in this case adds a lot more overhead to the site than necessary. Are there better approaches to handle something like this? On top of the performance issues, the animations done through JS are very choppy and I am hoping for a smoother effect.
Here's a CodePen of what I currently have above:
https://codepen.io/stufu/pen/GvJdxq
UPDATE
@FuriousD gave a good suggestion below in using CSS to accomplish this, while this is is closer to what I was hoping for, CSS animations cause a jump when hitting the end of the background position.
Here's a Codepen based on their answer but with a new problem of "jumping" after the animation completes: