Reputation: 1167
I am trying to have a slight delay on a gif animation so that it appears to have a left to right movement.
I have tried using the jQuery setTimeout method to wait a few seconds before showing the gif. The issue with this is that the gif is loaded at the same time as the other one and they end up being in sync with each other.
Here's is a basic example of what I am running into...
setTimeout(function() {
$('.dots-animation-delay').show();
}, 2500);
div {
float: left;
width: 33%;
text-align: center;
}
.dots-animation {
position: absolute;
padding-left: 5%;
}
.dots-animation-delay {
position: absolute;
padding-left: 5%;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
LEFT
<img class="dots-animation" src="https://s1.gifyu.com/images/dots.gif">
</div>
<div>
MIDDLE
<img class="dots-animation-delay" src="https://s1.gifyu.com/images/dots.gif">
</div>
<div>RIGHT</div>
I would like to alternate the animations so that once the left one fades out the right one will fade in. Is there a way to accomplish this with other jQuery methods or perhaps CSS keyframes?
Upvotes: 5
Views: 4676
Reputation: 1512
It is because the image is cached, so the second call is pulling the same image. You can use a cache buster so the browser thinks it is a different image.
Then, you want to dynamically add the image to the page with a random number of timeout, so it doesn't load when the first image loads. Otherwise, they will be in sync. You don't want to use a round number because there is a better chance that it will sync.
setTimeout(function() {
$('<img class="dots-animation-delay" src="https://picsum.photos/100?2">').appendTo($('.middle'));
}, 2638)
.float-left {
float: left;
width: 33%;
text-align: center;
}
.dots-animation {
position: absolute;
padding-left: 5%;
}
.dots-animation-delay {
position: absolute;
padding-left: 5%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<div class="float-left">
LEFT
<img class="dots-animation" src="https://picsum.photos/50?1">
</div>
<div class="float-left middle">MIDDLE</div>
<div class="float-left">RIGHT</div>
</div>
Upvotes: 4