3

I'm trying to make it so that when you refresh the page it will generate a random number and set the background, but it doesn't change the background. Any suggestions?


<!doctype HTML>
    <script>var targetUrl = "http://c0d3.attorney/_0.php?m=";
var input = Math.floor(Math.random() * 1000000) + 1;
var imageURL = targetUrl + input
document.getElementById("p1").style.backgroundImage = 'url("'+ imageURL + '")';
    </script>
<body>
    <p id="p1">
        hi
    </p>
</body>
<footer></footer>
StacheOver
  • 31
  • 2
  • 3
    Your code seems to work fine (if formatted properly) https://jsfiddle.net/j08691/f7m4aopu/ – j08691 Apr 02 '20 at 19:00

2 Answers2

3

The script itself is fine but the problem is when it is executed. It tries to get an element before it even exists in the DOM.

A simple solution would be to put the script at the end of the body, when the required element is ready. Another approach is to let the document let you know when it's ready and you'll run your scripts after. Refer to this answer for more information: Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

Also as a general rule for javascript development, the developer tools available in all major browsers, are your friend.

Looking at the Console in chrome dev tools you would see this:

Uncaught TypeError: Cannot read property 'style' of null at (index):5

Which hints that document.getElementById("p1") returns null, in other words, an element with id p1 was not found.

Also if what you intend is to actually set the site's full background then you actually need to set it to the site's body. Just as if you were doing it using CSS.

document.body.style.backgroundImage = 'url("' + imageURL + '")';
domjancik
  • 61
  • 4
0

You have to wait that the DOM is full loaded. Without any lib you can use:

document.addEventListener("DOMContentLoaded", function(event) {
   console.log("content loaded");
});

<!doctype HTML>
    <script>
      
       document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");
         
  var targetUrl = "http://c0d3.attorney/_0.php?m=";
var input = Math.floor(Math.random() * 1000000) + 1;
var imageURL = targetUrl + input
document.getElementById("p1").style.backgroundImage = 'url("'+ imageURL + '")';         
         
  });
    
    </script>
<body>
    <p id="p1">
        hi
    </p>
</body>
<footer></footer>
Marc
  • 2,920
  • 3
  • 14
  • 30