user2324827 user2324827 - 4 years ago 131
CSS Question

How do I change the background image every X seconds?

I have a

that fills the entirety of a page (portfolio style). The
has this style:

.image-head {
background: url('') no-repeat top center fixed;
background-size: cover;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
color: black;
text-align: center;

Basically, what I want to do is every X seconds change the
that the
points to for it's background image, but I am unsure on how to do this.

My markup currently looks like this:

<div class="image-head">
<div class="centering-hack">
<h1>Something HTML</h1>

What's the simplest/best solution here?


Edit: I'm using Bootstrap 3 if the JS library makes anything easier

Answer Source

Make an array with the images you want to use:

var images = [

We retrieve the div whose background you want to change:

var imageHead = document.getElementById("image-head");

You can now use setInterval to change the background image url every second (or whatever interval you want):

var i = 0;
setInterval(function() { = "url(" + images[i] + ")";
      i = i + 1;
      if (i == images.length) {
        i =  0;
}, 1000);

Here's a live example:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download