Ad

Changing Background Css With Javascript

- 1 answer

In the website http://scoopsgelato.co.uk/, when their webpage loads the background image at the top of the page changes after around 10seconds.

I want to know how to do a basic version of this. Code that sets the background-image property in the css to cycle through images.

I tried for a few hours to get it myself but I could not figure it out.

Ad

Answer

Since you were looking for something simple, here is one solution at least for some inline CSS.

var imgArry = ["http://dummyimage.com/200x200/cf90cf/555770.png&text=pic+1", "http://dummyimage.com/200x200/c99011/555770.png&text=pic+2", "http://dummyimage.com/200x200/cc5601/555770.png&text=pic+3"];
function backgroundImageSlider(elem, imgs, speed){
   var index = 0;
   var timer = setInterval(function(){
      elem.style.backgroundImage = "url(" + imgs[index] + ")";
      index++
      if(index == imgs.length){
         index = 0;
      }
   }, speed);
}

backgroundImageSlider(document.getElementById("imageDiv"), imgArry, 10000);

Here is a JSFiddle. https://jsfiddle.net/o3zhwhdp/1/

Ad
source: stackoverflow.com
Ad