Adding JavaScript to a file using the <script> element
Files in this demo
├─ index.html └─ script.js
JavaScript is the third language of the web. HTML is the content, CSS is the look, and JavaScript is the behaviour ~ anything that reacts, changes, or calculates.
You attach it with <script>, and there are two ways.
A separate file
<script src="script.js"></script>
This is what you want. Your JavaScript lives in its own file, and every page can share it.
Straight into the page
<script>
console.log("hi");
</script>
Handy for a quick test. Fine to start with.
Where the tag goes matters
Put <script> at the bottom of the <body>, just before </body>.
If it goes in the <head>, the script runs before the page’s HTML exists ~ so any attempt to find an element on the page comes back empty and you get an error. It is a genuinely confusing bug the first time.
(The other fix is <script src="script.js" defer></script> in the head, which tells the browser to wait. Either is fine. Bottom of the body is easier to remember.)
The console
Open the console panel at the bottom right. console.log() prints to it, and it’s where errors show up. It’s the single most useful tool you have while learning ~ keep it open.
Click to resume
Use the console below.