Help, Javascript code not being called

Hi new here, been looking up the web why my javascript is not being called in my html code. On the debug/console I get
"

"
trying to recreate a game my teacher made us do a few years back but better (old style spaceshooter type game) have 3 set of files: html, css and js.
here is my html:

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" >
<meta http-equiv="Content-Type" content="text/html">
<link rel='stylesheet' href="looks.css">
<title>Spaceshooter</title>
<script src="script.js"></script>
</head>
<body>
<h1>
<center>Spaceshooter</center>
</h1>
<div>

<canvas id="mycanvas" style="height: 600px; width: 100%;"></canvas>

</script>
</div>
</body>
</html> 

and here is my css:


body {
	background-color: #8B008B;
}
h1 {
	font-family: "Lucida Console";
	font-weight: bolder;
	text-shadow: 2px 0 #424242;
}
div {
	height: 600px;
	width: 95%;
	margin-left: auto;
	margin-right: auto;
	margin-top: 35px;
	background-color: black;
}

and here is my js:


var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

ctx.fillStyle="#FF0000";
    ctx.fillRect(0,0,150,75);
console.log("Help me!");

What I want with this game is for it to be 3 files in a folder so I can just rar it and send it to friends. so I just want them to be able to open the html and not do anything more (i.e set up a localhost for it to work)
But my .js is not working. the html and css work fine but I can’t for the life of me find anything that helps online with my problem.
some info you might ask for:
The files are in: D:\Stuff\spaceshooter (have tried to add the entire file path, with and without file://)
I am using firefox, but tried chrome and MS edge aswell.
Have tried to move the “script src=”“></script” around and did not change anything. did also add type=“text/javascript” but also nothing.

Thanks in advance for any help, and hope all you have a great day.

Hi,

Rearrange your code, so that the JS runs after the HTML is present on the page.

Like so:

<!DOCTYPE html>
<html>
  <head>
  <meta charset="UTF-8" >
  <link rel='stylesheet' href="looks.css">
  <title>Spaceshooter</title>
</head>
<body>
  <!-- content here -->

  <script src="script.js"></script>
</body>
</html>

Firstly, your JS is being called. It just has an error!

Secondly, you need to be consistent - mycanvas or myCanvas.

Thirdly, @James_Hibbard has beaten me to Thirdly! :slight_smile:

2 Likes

thanks, did not even notice that the C was bigger in my js code. works now

…and here it all is in a zip file…

mrdonkyman.zip (1.2 KB)

:biggrin:

cothead

You can also defer loading js files by using the “defer” attribute in the script tag and still keeping it within the head tag.

< script defer src=“script.js”>< /script>

For further details about defer and async, I find the following article to be highly instructive.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.