skip to Main Content

As part of my learning, I have manage to set the background image of my page and change the image every 10 seconds.
However, the change between images is harsh with a white background shown before the next image. Is there anyway I can fade each image in/out? All help will be appreciated.


  * { margin: 0; padding: 0; }
  
  html { 
    background: url(/cover1.webp) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
  }

</style>

<div class="hero is-fullheight">

</div>
<script>
  function changeBg(){
    const images = [
      'url("/cover1.webp")',      'url("/cover2.webp")',      'url("/cover3.webp")',      'url("/cover4.webp")',
      'url("/cover5.webp")',      'url("/cover6.webp")',      'url("/cover7.webp")',      'url("/cover8.webp")',
      'url("/cover9.webp")',      'url("/covera.webp")',      'url("/coverb.webp")',      'url("/coverc.webp")',
    ]

    const selector = document.querySelector('html');
    const bg = images[Math.floor(Math.random() * images.length)];
    selector.style.backgroundImage = bg;
  }
  setInterval(changeBg, 10000)
</script>

2

Answers


  1. Just changing the html style tag produced the effect I wanted:

      html { 
        background: url(/cover1.webp) no-repeat center center fixed; 
        background-size: cover;
        -webkit-transition: background 1000ms ease-in-out 1000ms;
        -moz-transition: background 1000ms ease-in-out 1000ms;
        -o-transition: background 1000ms ease-in-out 1000ms;
        transition: background 1000ms ease-in-out 1000ms;
      }
    
    Login or Signup to reply.
  2. You can add animation properties to your images. For example if you have images with class "image".

    CSS
    .image {
      animation: fade 1s ease-in-out;
      @keyframes fade {
        0% { opacity: 0; }
        100% { opacity: 1; }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search