1

I would like to make a full page CSS background change to a different image every few seconds. I have tried searching for a simple solution, but all the examples I find have fade in/fade out transitions.

1 Answers1

0

To change the background image of an element without transition effects, you can use CSS @keyframes animation, then specify steps() as the easing function with the relevant arguments passed.

body {
  animation: change-bg 10s steps(2, jump-none) forwards infinite;
}

@keyframes change-bg {
  0%, 100%  { background: url(https://dummyimage.com/500/00ff00/000); }
  20% { background: url(https://dummyimage.com/500/ff0000/000); }
  40% { background: url(https://dummyimage.com/500/0000ff/000); }
  60% { background: url(https://dummyimage.com/500/666666/000); }
  80% { background: url(https://dummyimage.com/500/ffee66/000); }
}

You may also achieve similar functionality using JavaScript, with the setInterval function, and pass the delay time in milliseconds.

const slides = [
  "https://dummyimage.com/500/00ff00/000",
  "https://dummyimage.com/500/ff0000/000",
  "https://dummyimage.com/500/0000ff/000",
  "https://dummyimage.com/500/666666/000",
  "https://dummyimage.com/500/ffee66/000"
];

let index = 0;
  
setInterval(() => {
  document.body.style.backgroundImage = `url(${slides[index]})`;
  index = index < slides.length - 1 ? index + 1 : 0;
}, 2000); // every 2 seconds

I would suggest preloading the images before starting the animation.

Vektor
  • 697
  • 5
  • 14