How to add your js code to html, with files?

You’re getting this error because those are smart-quotes instead of regular quotes. :slightly_smiling_face:

2 Likes

It doesn’t do like that for me.
Screenshot from 2021-01-26 12-29-59

I switched them around now it works.

Thanks for the help and everyone else for helping out. :grinning:

3 Likes

Just some more info. This code…

document.getElementById('LineChart')

…can not run before the DOM (the document) is loaded.

It is looking for an element with the id LineChart and if it looks for that element before the element has loaded it will fail.

You have a few choices:

  1. Load the script after the HTML, usually at the bottom before the closing </body>
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>

  <body>
    <h1>Some HTML</h1>
    <canvas id="LineChart"></canvas>
	
    <script src="./yourCode.js"></script>
  </body>

</html>
  1. Use defer or async attributes on the script tag.
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Document</title>
	<script defer src="./yourCode.js"></script>
  </head>

  <body>
    <h1>Some HTML</h1>
    <canvas id="LineChart"></canvas>
  </body>

</html>
  1. Use a DOMContentLoaded event.

yourCode.js

window.addEventListener('DOMContentLoaded', (event) => {
  // add all your code inside here
  console.log(document.getElementById('LineChart'));
});

It might look complicated but it’s really not.

Think of document.getElementById('LineChart') like a person’s name, if you call the name before the person is in the room they will not hear it.

3 Likes

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