0
var Period =1;

        if(Period==1){
            document.getElementById("Main").style.backgroundImage = "url('Main_Background_Grass_1.png')";
        }

For some reason this wont work. The image location is correct but im sure there is something wrong.

im pretty new to javascript

heres more code

<script type="text/javascript">

        var Knowledge = 0;
        var Period =1;

        if(Period==1){
            document.getElementById("Main").style.backgroundImage = "url('Main_Background_Grass_1.png')";
        }

</script>

<div id="Main">

    <div id="Toolbar">
        Oh noes! Something Went Wrong
    </div>
</div>

the image wont show up at all

King Kwame
  • 67
  • 1
  • 1
  • 9

2 Answers2

4

The element isn't found at the time you call your function, place the javascript right before the closing body tag

<div id="Main">

    <div id="Toolbar">
        Oh noes! Something Went Wrong
    </div>
</div>

<script type="text/javascript">

        var Knowledge = 0;
        var Period =1;

        if(Period==1){
            document.getElementById("Main").style.backgroundImage = "url('Main_Background_Grass_1.png')";
        }

</script>
baao
  • 71,625
  • 17
  • 143
  • 203
1

Uncaught TypeError: Cannot read property 'style' of null
That's because the element wasn't loaded yet. There are two ways to make sure a code runs only when a page is ready. One is to put the code at the bottom of the body, so the page has already been loaded. The other is to put it in an event listener for the window load event:

<script type="text/javascript">
  window.addEventListener("load", function(e) {

  // code goes here

  });
</script>

Which one is the best practice? That's an eternal debate. I prefer the listener so that the code is all at the top, but many would disagree.

Domino
  • 6,314
  • 1
  • 32
  • 58