0

I have a simple full screen background image as shown below:

body {
 /* The background image used */
 background-image: url("../images/bg-one.jpg");

 /* Full height */
 height: 100vh; 
 width: 100vw;

 /* Hide scroll */
 overflow-x: hidden;
 overflow-y: hidden;

 /* Center and scale the background image nicely */
 background-position: center;
 background-repeat: no-repeat;
 background-size: cover;
}

I would like to know how I can make the background image change every 5 seconds with a fade in/out transition. Sorry if this seems like a newbie question but I'm just starting out learning Js/Jquery.

My second question would be is it possible to do this using pure CSS3 or would js/jquery work better?

Many thanks, Aidan

Aidan
  • 470
  • 3
  • 7
  • 16
  • Between this https://stackoverflow.com/questions/34690104/make-javascript-change-background-image-every-5-seconds and this https://stackoverflow.com/questions/34669608/javascript-foreach-loop-through-an-array-of-hex-values-using-settimeout-to-loop, I think you can get fashion a solution. – Marc Aug 24 '18 at 20:11
  • Look here for answers to someone else who asked a similar question: [CSS3 background image transition](https://stackoverflow.com/questions/9483364/css3-background-image-transition) – Raptord Aug 24 '18 at 20:16
  • You can't animate background-image (so you can't make fade-in out efect) but you can make 2 elements each over (absolute positioned). Timeout with pure CSS is not possible neither. – Jax-p Aug 24 '18 at 20:55

2 Answers2

0

I have created a test case for you using jquery: https://codebrace.com/editor/afec3e661

With pure js you may replace jquery with document.body.style.backgroundImage = "url('" + a[i++] + "')";

Test case for background change with fadein/out effect: https://codebrace.com/editor/afef034d6

0

You can't make fade-in fade-out animation on background-image, because this atribute cannot be animated. Instead of it, you can make 2 fixed elements which are positioned over each other.

You can't make timeout/interval in plain CSS, you'll have to use JS. I've used setInterval function which is switching .active state of two elements, class .active adds to element opacity with transition - example is here: https://jsfiddle.net/2cxmeq7p/

Jax-p
  • 7,225
  • 4
  • 28
  • 58