2

If var raster = document.querySelector ("canvas") is in the HTML file, raster is defined and declared. However, I'd like to have everything in my js file, only function calls in my HTML. When I try putting var raster... in the .js file, it keeps coming up null.

Is there any way to have document.querySelector point to the associated HTML file?

// this doesn't work
//var raster = document.querySelector ("canvas").getContext ("2d");

function drawSquare (w,h) {

raster.fillStyle = "blue";
raster.fillRect (0,0,w,h);
}
<!DOCTYPE html>

<html>

    <head>
        <meta charset="utf-8">
        <title>IFS</title>
        <script src="IFS.js"></script>
    </head>

    <body>
        <canvas width="500" height="500"></canvas>
        <script>var raster = document.querySelector ("canvas").getContext ("2d");
        drawSquare (500,500);</script>
    </body>

</html>
Ouroborus
  • 12,316
  • 1
  • 27
  • 51
failure
  • 185
  • 1
  • 2
  • 11
  • What is IFS.js? – Ouroborus Mar 31 '17 at 18:29
  • Sorry. The top code block is a copy-paste from the file IFS.js. The bottom block is IFS.html. – failure Mar 31 '17 at 18:31
  • 1
    Your script file is in the head, the element is in the body, when you put your javascript in the head, the element doesn't yet exist when it's trying to find the element in the body. – adeneo Mar 31 '17 at 18:31

1 Answers1

19

Try moving <script src="IFS.js"></script> to the end of the HTML code, before the closing <body> tag, instead of having it at the <head>.

The issue is caused because the script is loaded before the <canvas> is rendered, so document.querySelector ("canvas") returns null.

LostMyGlasses
  • 2,614
  • 15
  • 26
  • I doubt that. Nothing in IFS.js is immediately dependent on the document. – Ouroborus Mar 31 '17 at 18:32
  • Putting src="IFS.js" after canvas but before the drawSquare call worked. Thanks very much, this is very educational! So JavaScript parses as it goes, doesn't compile. I see now. – failure Mar 31 '17 at 18:34
  • @LostMyGlasses `document.querySelector("canvas")` isn't in IFS.js and does already follow ``. – Ouroborus Mar 31 '17 at 18:34
  • Oh, I moved it, too. Forgot to mention that. As it stands now: var raster is in the js file, not the HTML, and the js file is defined after canvas but before the drawSquare call. – failure Mar 31 '17 at 18:35
  • @failure Generally, Javascript needs to come after, time-wise, the things it effects. So if you're immediately executing the Javascript (which you are) the javascript needs to be in the code after the elements it effects. – Ouroborus Mar 31 '17 at 18:38