JavaScript in a Web Page
So far, your programs have printed text into the console. But JavaScript was made for web pages: almost every page you visit uses it to react to clicks, show new content or check what you've typed. In this lesson, you'll learn to change a web page with JavaScript, and at the end, you'll build a small to-do list.
A web page is written in HTML. HTML isn't a programming language: it describes what is on the page, such as headings, paragraphs and buttons. Each of these parts is an element, written with tags:
<h1>Weather</h1>
<p>It's sunny today.</p><h1> is an opening tag and </h1> a closing tag (with a slash); between them is the content of the element. h1 is the main heading, p a paragraph. Elements can contain other elements. The whole page is in the html element, which has two parts: head with information about the page, such as its title, and body with everything you see on the page. Every page also needs the lines <!DOCTYPE html> and <meta charset="utf-8"> to be displayed correctly; you don't have to worry about them now.
In this lesson, the editor has two files, and you switch between them with the tabs above it: script.js is your JavaScript program and index.html is the page. The preview shows the page, and under it is the console, where you see what console.log() prints and any errors.
The page loads the program with the script element:
<script src="script.js"></script>src="script.js" is an attribute: extra information written in the opening tag as name="value". The src (source) attribute says which file to load. There's nothing between the tags, but the closing tag </script> must be there anyway.
Put the script element at the end of body, just before </body>. Why there? The browser reads the page from top to bottom and runs a script as soon as it gets to it. A script at the top of the page would run before the browser has read the elements below it, so it couldn't find them.
The script runs once, when the page loads. Each time you click Run, the page loads again, and the script runs again.
script.js already contains a short program: it prints a message into the console and changes the main heading. You'll learn how it works in the next exercise. For now, nothing happens, because the page doesn't load the script yet.
Instructions
In index.html, add <script src="script.js"></script> at the end of body, on a new line just before </body>. Click Run: the heading changes to JavaScript works! and the console shows Hello from script.js!.
Start programming for free
1/10