Home > Blockchain >  How to check if Background image is loaded - when the image is as a background url in a css file
How to check if Background image is loaded - when the image is as a background url in a css file

Time:11-25

I have been looking at different answers on how to check if a background image has loaded, however, majority of them are for if the image is set in the html code.

I have my image as a background url in a css file:

.container{
    background-image: url(/images/rickandmorty.jpg) !important;
    background-repeat: no-repeat;
    background-size: cover;
}

At the moment, the text is loading before the picture. Any way around it using javascript?

Thanks

CodePudding user response:

I'm not sure but you can try add onl oad event on html objet like this:

<div class="container" onl oad="myFunction">...</div>

CodePudding user response:

I know this is not what was asked - but I would like to advocate using images over background-images. It makes the implementation much more flexible (animations etc.), allows optimizing for resolution and device (srcset), provides better accessibility (alt tags), easy event listening etc.

To make images work like background you just need a picture wrapper and a bit of css (object-fit: cover)

Here is a small example using onl oad to trigger animation

function onImageLoaded() {
  document.querySelector('header').classList.add('loaded')
}

function onImageError() {
  alert('I\'m starting to work up some anxiety about this whole thing!')
}
* {
  box-sizing: border-box;
  position: relative;
}

header {
  aspect-ratio: 21/9;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1rem;
  color: white;
  text-shadow: 0 0 .25em rgba(0, 0, 0, 0.4);
  background: #869F63;
  z-index: 0;
  overflow: hidden;
}

picture {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: block;
  z-index: -1;
  overflow: hidden;
}

picture img {
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

h1 {
  will-change: transform;
  transition: transform 2000ms;
  transform: translateY(50vh);
  opacity: 0;
}

img {
  will-change: transform;
  transition: transform 2000ms;
  transform: scale(2);
  opacity: 0;
}

.loaded h1,
.loaded img {
  transform: none;
  opacity: 1
}
<header>
  <picture>
    <img src="https://assets.codepen.io/68939/rickandmorty.png" width="680" height="380" alt="Rick & Morty...." onload="onImageLoaded()" onerror="onImageError()" />
  </picture>
  <h1>Rick & Morty</h1>
</header>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related