0

I am designing a bootstrap based website. I have a navigation bar and below it there is a full screen background image. I want to change the the background image after some seconds. The image is inside a header tag and has some text over it in the center. The code for header:-

<header id="image">
    <div class="header-content">
        <h1>Hello</h1>
    </div>
</header>

The css for header:-

header {
 position: relative;
 width: 100%;
 min-height: auto;
 -webkit-background-size: cover;
 -moz-background-size: cover;
 background-size: cover;
 -o-background-size: cover;
 background-position: center;
 background-image: url('images/1.jpg');
 text-align: center;
 color: white;
}
.header1 {background-image: url('images/1.jpg');}
.header2 {background-image: url('images/2.jpg');}
.header3 {background-image: url('images/3.jpg');}

The javascript i tried:-

 <script type="text/javascript">
function run(interval, images) {
var int = 1;

function func() {
    var d = document.getElementById("image");
    d.className += "header"+int;
    int++;
    if(int === images) { int = 1; }
}

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

run(5000, 3);
</script>

I tried to change the class property after an interval but it didn't work.

I want to change the background-image of the header lets say after every 10 seconds to 2.jpg and then to 3.jpg and then back to 1.jpg using plain javascript. Please provide a way as i am unable to think of a way to change the image. I would be highly grateful if anyone can help.

1 Answers1

0

This will take care of what you are looking for, assuming that your images are named with digits.

var counter = 1; //instantiate a counter
var maxImage = 5; //the total number of images that are available
setInterval(function() {
    document.querySelector('header').style.backgroundImage = "url('images/" + (counter + 1) + ".jpg')";
    if (counter + 1 == maxImage) {
        counter = 0; //reset to start
    } else {
        ++counter; //iterate to next image
    }
}, 10000);
Andrew
  • 171
  • 1
  • 8