0

I want to make it so when ever I reload the page, the background gets chosen randomly.

function switchBG(urlThing) {
        document.getElementById("bg-img").style.display="block";
        document.getElementById("bg-img").style.backgroundImage="url(urlThing)";
    }

    var n = Math.floor((Math.random() * 2) + 1);

    if (n == 1) {
        switchBG('back1.jpg');
    }
    else if (n == 2) {
        switchBG('back2.jpg')
    }

I tried that, but nothing happened.

Edit: This is the div. It's the first thing under the tag.

<div id="bg-img"></div>
YaYPIXXO
  • 17
  • 5

2 Answers2

0

You need to concatenate the variable like this:

document.getElementById("bg-img").style.backgroundImage="url(" + urlThing + ")";
nsayer
  • 799
  • 2
  • 8
  • 21
0

I am assuming bg-img is the <img> tag. this is how you can do it

function switchBG(urlThing) {
    document.getElementById("bg-img").style.display="block";
    var loc = window.location.pathname;
    var dir = loc.substring(0, loc.lastIndexOf('/'));
    document.getElementById("bg-img").src=dir + urlThing;
}
pilku
  • 120
  • 3
  • 8