-3

I have some javascript code here, that randomly changes the background of the landing page of my website. This is the code:

    var bigSize = [ 
                    "url('assets/bg/front1.jpg')",
                    "url('assets/bg/front2.jpg')",
                  ];
    var random = Math.floor(Math.random() * 2) + 0;
    document.getElementById("front").style.backgroundImage=bigSize[random];

When I load the page and take a look at my console, it gives the following error:

background.js:6 Uncaught TypeError: Cannot read property 'style' of null
    at background.js:6

However, when I run the exact code through the console, the script works perfectly. Can anyone help me with this? Thanks in advance!

1 Answers1

0

The problem might be that you're inserting the script tag before the body tag. Insert the script tag after the body tag. Javascript is not able to find your element, it means it hasn't been rendered to the browser yet and when you're accessing it, it is throwing an error.

Ajay Gaur
  • 4,400
  • 4
  • 31
  • 49