Spencer Davis
Spencer Davis

Reputation: 37

Using Javascript to change background image of a div

So I've been struggling with my Javascript skills using my books to get through it but I've finally found something that I can't seem to cobble together with just the books alone. What I'm trying to do is change the css background-image of a div with an id of belowNav every couple-few seconds below is the code I have that is returning no errors in the console but effectively not functioning(literally not doing anything) If someone with more JS skills than I could help it would be much appreciated :)

    setInterval(function changeImage(){
    var el = document.getElementById("belowNav");
    var currentImage = 0;
    var backImage = ["img2.png",
                        "IMG_3880.JPG",
                        "IMG_6629.JPG",
                        "IMG_6552.JPG",
                        "IMG_4090.JPG",
                        "IMG_0005.JPG",
                        "IMG_0041.JPG",
                        "IMG_6544.JPG",
                        "IMG_6628.JPG",
                        "IMG_5168.JPG",
                        "coffee.jpg"]
    var lastImage = backImage.length+1;
    for (var i = 0; i < 10; i++); {
    currentImage = i;
    el.style.backgroundImage = "%resource("+backImage[currentImage]+")%";
        if(i == 10){
        i = 0
            }//end if
        }//end for
    }, 2000);//end Function

Upvotes: 0

Views: 159

Answers (2)

showdev
showdev

Reputation: 29188

I made a few modifications to your code.

Primarily, your code loops from 0 to 10 upon each call to the changeImage function. It seems that you want to advance the image index only once per call, in order to change the background to the next image in the array.

I've used url() for the background image, per CSS background-image.

I've also moved variable definitions outside of the function, as they do not need to be redefined upon each call.

var el = document.getElementById("belowNav"),
  backImage = [
    "https://via.placeholder.com/400x150?text=One",
    "https://via.placeholder.com/400x150?text=Two",
    "https://via.placeholder.com/400x150?text=Three"
  ],
  imageIndex = 0;


function changeImage() {
  el.style.backgroundImage = "url('" + backImage[imageIndex] + "')";
  imageIndex++;
  if (imageIndex >= backImage.length) {
    imageIndex = 0;
  }
}

setInterval(changeImage, 2000);
changeImage();
div#belowNav {
  width: 400px;
  height: 150px;
}
<div id="belowNav"></div>

Upvotes: 2

Justin B. Evans
Justin B. Evans

Reputation: 21

Almost there! The CSS background property is wrapped within a url('') wrapper, so this line:

el.style.backgroundImage = "%resource("+backImage[currentImage]+")%";

Should be

el.style.backgroundImage = "url('"+backImage[currentImage]+"')";

I wasn't sure what %resource is referring to, so I removed those references. Credit to imnancysun for writing this first though!

Upvotes: 1

Related Questions