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

8
  • 1
    Please define "wont work". Any errors in the console? Background image doesn't appear? A wrong image appears? Something else? Commented Jul 23, 2015 at 17:53
  • yea its the exact ID and background image dosen't appear Commented Jul 23, 2015 at 17:53
  • Browsers have consoles that display error messages. In chrome, try Ctrl+J. In Firefox, Ctrl+K. Commented Jul 23, 2015 at 17:54
  • How about the console, can you see any error messages? Commented Jul 23, 2015 at 17:54
  • Where is the code placed? My bet is it's in the head Commented Jul 23, 2015 at 17:55

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.