Gagandeep Singh
Gagandeep Singh

Reputation: 13

How to Prevent flicker problem in css animation?

I am trying to make a slider using CSS @Keyframes Animation. It works smoothly when I used it for the first time with small size [1100px width and 400px height].

But when I expand the slider and image size for my website, I increase the height and width [1280 * 640]. Then my images are fliker at each interval just for first time, after first time flicker of each image, slider work smoothly.

But I want to prevent it in first time.

CSS:

.slider{
    position: relative;
    top: 0px;
    left: 0px;
    background: url(1.jpg);
    height: 600px; width: 1263.1px;
    margin-bottom: 20px;
    animation: slideshow 10s infinite;
}

@keyframes slideshow{
    25% { background: url(1.jpg); }
    50% { background: url(2.jpg); }
    75% { background: url(3.jpg); }
    100% { background: url(1.jpg); }
}

HTML:

<div class="slider"></div>

Upvotes: 0

Views: 931

Answers (1)

Krisk&#243; Tam&#225;s
Krisk&#243; Tam&#225;s

Reputation: 111

That's because the images haven't loaded, and they only start loading when the animation starts. To prevent this flickering, you can use the onload event in Javascript:

<div class="slider"></div>
<style>
    .slider{
        background-image: url("1.jpg");
        background-repeat: no-repeat;
        background-size: cover;
        height: 540px;
        width: 960px;
    }
    .slider.loaded{
        animation: slideshow 10s infinite;
    }
    @keyframes slideshow{
        0%{
            background-image: url("1.jpg");
        }
        25%{
            background-image: url("2.jpg");
        }
        50%{
            background-image: url("3.jpg");
        }
        75%{
            background-image: url("4.jpg");
        }
    }
</style>
<script>
    var images = [
        "1.jpg",
        "2.jpg",
        "3.jpg",
        "4.jpg"
    ];
    function loadImg(i){
        if(images[i] != undefined){
            var img = new Image();
            img.src = images[i];
            img.onload = function(){ // detect if image has been loaded
                i++;
                loadImg(i);
            }
        }
        if(images.length == i) // adding class 'loaded' when all images finished with loading
            document.getElementsByClassName("slider")[0].classList.add("loaded");
    }
    loadImg(0);
</script>

NOTE: I managed to prevent the flickering, but

This only works perfectly in Chrome

Firefox can't animate the images, but the images are still shown

This is absolutely not working in IE / Edge

Upvotes: 1

Related Questions