0

I've tried to make my website change background every 10 seconds. It was successful. Now, I want to fade them in and fade them out, so they will appear smoothly. I've searched other forumpages and found related questions, but I wasn't able to understand the answers well.

Javascript:

function run(interval, frames) {
var int = 1;

function func() {
    document.body.id = "b"+int;
    int++;
    if(int === frames) { int = 1; }
}

var swap = window.setInterval(func, interval);
}

run(10000, 6); //milliseconds, frames

CSS:

#b1 { background-image: url("standaard01.jpg"); }
#b2 { background-image: url("standaard02.jpg"); }
#b3 { background-image: url("standaard03.jpg"); }
#b4 { background-image: url("standaard04.jpg"); }
#b5 { background-image: url("standaard05.jpg"); }
#b6 { background-image: url("standaard06.jpg"); }
#b7 { background-image: url("standaard07.jpg"); }
#b8 { background-image: url("standaard08.jpg"); }
#b9 { background-image: url("standaard09.jpg"); }
#b10 {  background-image: url("standaard10.jpg"); }
  • Not sure but maybe CSS transition-duration would work? Try adding a `transition-duration: 10s`to your style classes. – Quagaar Nov 13 '16 at 01:07
  • 1
    https://stackoverflow.com/questions/9483364/css3-background-image-transition – Alvaro Nov 13 '16 at 01:13

1 Answers1

-1

Unfortunately it's not possible to transition between two images set to the background of a single element. (correction: it is, by animating the background-image property of an element - given browser support)

However, you can fade one element out while another element lays behind it.

Jquery has a method called .fadeToggle() that you could use in this case.

Set up a "stack" of img elements or divs with bg images, positioned on top of eachother, with the position:absolute, left, and top CSS properties.

Then, in your javascript loop, every 10 seconds, .fadetoggle() the currently visible div, revealing the next image. You could keep track of the state with an index variable.

Upon reaching the final element, fade the top image again. Then before the second element fades, .show() the remaining elements so they once again visible for the revealing.

A note about z-index: The CSS property z-index will position elements either in front, or behind other elements. So it would be wise to set the correct z-index of each item either in it's css class, or programmatically on loading the page.

Image size note: If the images or divs are different dimensions, you would fade one in, while fading the other out. From here we can talk about different crossfading methods but that's beyond the scope of this discussion

Good luck :)

Andy Mac
  • 369
  • 2
  • 9