Milloz
Milloz

Reputation: 55

Background crossfade transitions javascript and css

I am new to javascript. I made a simple code that in javascript will randomly change my background every 5 seconds, however, it looks horrid.
Both of loading the picture and the transition is jumpy and doesn't look nice at all. When I google this problem all the code looks super complicated, I am not allowed to use external links for help either(it's a school project).

What I want is to implement crossfading transitions into my code, and I have seen people do it using CSS but for that, you have to add every single picture and blah blah blah, I want it to be reusable, for me to write it once and then if I add more pictures I won't have to change anything, hope you guys understand and hope you can help!!! :)

Code:

function random_pic() {
  // image array
  var images = ["url(1.jpg)", "url(2.jpg)", "url(3.jpg)", "url(4.jpg)"];

  // execute code every 5 seconds
  window.setInterval(function() {
      // create a random number between 0 and 4
      var num = Math.floor(Math.random() * 4);
      // set the background to one of the images in the array
      document.body.style.backgroundImage = images[num];
    },
    5000);
}

random_pic();

Upvotes: 1

Views: 814

Answers (1)

Evert vd H.
Evert vd H.

Reputation: 343

I'm reading that you have two different issues that you are trying to solve. The biggest issue is the crossfading issue. The other issue is the performance and loading of the images.

As this is a school assignment I think it's not a good idea to share the exact code that will make this work, but I'll give you some pointers that you can use to get to the desired result.

  1. For crossfading you will need to have 2 elements that use a fade animation (css opacity) to create the effect.
  2. Once the element that fades out is completely faded out, swap the source of the image for a new one and fade it back in while the other element fades out and repeat the process.
  3. By changing the source of the image when it's not visible for the user you will probably have a better look and feel because the image will be loaded before it's shown to the user.
  4. To get it performant, make sure that the images that you are using are as small as possible in file size. For reference I would try to keep them under a 100kb to start with.
  5. You could also look into preloading the images, but that might be a step too far for a school assignment.

Hope this helps. Good luck.

Upvotes: 3

Related Questions