Reputation: 3
I'm trying to change my background only one time after 1 second of loading. Then Second Image will be show.
I just want to show the first image only for 1st one second then want to show second image.
HTML
<div id="image-head" class="image-head">
</div>
CSS
.image-head {
background-image:url(background_image_1.png);
background-size: cover;
background-repeat: no-repeat;
background-position: top center;
}
JS
var images = [
"http://example.com/wp-content/uploads/2019/05/background_image_2.jpg"
]
var imageHead = document.getElementById("image-head");
var i = 1;
setInterval(function() {
imageHead.style.backgroundImage = "url(" + images[i] + ")";
i = i + 1;
if (i == images.length) {
i = 0;
}
}, 1000);
Please let me know how can I do it.
Thanks!
Upvotes: 0
Views: 937
Reputation: 183
@DominikMatis has the correct answer, but I wanted to help clean the code up a bit.
var image = "http://example.com/wp-content/uploads/2019/05/background_image_2.jpg";
var imageHead = document.getElementById("image-head");
setTimeout(function() {
imageHead.style.backgroundImage = "url(" + image + ")";
}, 1000);
This makes more sense since you're only replacing the image once, with a single image. What you had before would work great for replacing several images at a specified time interval.
Upvotes: 0
Reputation: 2146
You need to use setTimeout
instead of setInterval
And you don't even need that array
setTimeout(() => document.getElementById("image-head").style.backgroundImage = `url("http://example.com/wp-content/uploads/2019/05/background_image_2.jpg")`, 1000);
Upvotes: 2
Reputation: 1325
You should replace
setInterval(function() {
imageHead.style.backgroundImage = "url(" + images[i] + ")";
i = i + 1;
if (i == images.length) {
i = 0;
}
}, 1000);
by
setTimeout(function() {
imageHead.style.backgroundImage = "url(" + images[i] + ")";
i = i + 1;
if (i == images.length) {
i = 0;
}
}, 1000);
The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
The setTimeout() method of the WindowOrWorkerGlobalScope mixin (and successor to Window.setTimeout()) sets a timer which executes a function or specified piece of code once the timer expires.
See document
Upvotes: 1