Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.querySelector doesn't work in .js file [duplicate]

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>
like image 749
failure Avatar asked Jul 09 '26 02:07

failure


1 Answers

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.

like image 194
LostMyGlasses Avatar answered Jul 11 '26 15:07

LostMyGlasses



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!