Arsi
Arsi

Reputation: 176

How to load animation when background has loaded

What I want to do is to add a class to an element once a background image has been rendered.

Code looks something like this:

#banner {
  background-image: url('/img/bg-banner.webp');
}

#banner-title {
  line-height: 1;
  font-family: 'Oswald';
  font-weight: bold;
  text-align: right;
}

#banner-title.start {
  animation-name: fade-in-title;
  animation-fill-mode: forwards;
  animation-timing-function: cubic-bezier(0.33, 0.99, 0.76, 1);
  animation-delay: 1s;
}
<div id="banner">
  <p id="banner-title">Some text</p>
</div>

So my question is how do I add 'start' class to #banner-title once the background-image of #banner has finished loading?

p.s. Onload on #banner does not work

Upvotes: 0

Views: 468

Answers (2)

Pieter Smagge
Pieter Smagge

Reputation: 1

If you need to be sure that the background image has been loaded before some javascript code is executed, you might try this (somewhere after the banner):

var img = new Image();
img.onload = function () {
    document.getElementById('banner').classList.add('start');
    // or some other code that requires the image to have been loaded
}
img.src = "/img/bg-banner.webp";

NB: You will still need the background-image declaration in your css:

#banner {
    background-image: url('/img/bg-banner.webp');
}

This should work around any lazy loading of background images by the browser. I think it's reasonable to assume that if the image has been loaded into the img variable, it will also be available as a background image for the banner.

I know it's a bit of a hack, but it worked for me.

Upvotes: 0

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

Use document.addEventListener see below...

<script>    
document.addEventListener('DOMContentLoaded', function backgroundLoaded() {
        //do whatever you want
    });
</script>

Upvotes: 1

Related Questions