Zack105 Zack105 - 2 years ago 75
HTML Question

Change Background Image in a loop

To me, this seems like a simple idea- when you click a div, the background image of that div changes. So far, I've tried this with colors (put color names in the array, change "box.style.backgroundImage" to "box.style.backgroundColor")
It works fine with colors, but not with images. Any idea why?

Javascript:

var box = document.getElementById('box'),
imgs = ['/image.jpg', '/image2.jpg'];

box.onclick = function () {
img = imgs.shift();
imgs.push(img);

box.style.backgroundImage = img;
};


HTML:

<div id='box'></div>


CSS:

#box {
background: url("https://priteshgupta.com/wp-content/uploads/2011/06/html-ipsum.png");
width:200px;
height:200px;
margin:50px;
}

Answer Source

You still need url("..."):

box.style.backgroundImage = 'url("' + img + '")';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download