Line At A Time
Lesson 8: Click Events
Click Events Run code the moment a button is clicked.
index.html
1<!doctype html>
2<html>
3 <head>
4 <title>Clicks</title>
5 </head>
6 <body>
7 <h1 id="greeting">Hello!</h1>
8 <button id="magic">Click me</button>
9 <script src="script.js"></script>
10 </body>
11</html>
script.js
1const btn = document.getElementById('magic');
2btn.addEventListener('click', () => {
3 document.getElementById('greeting').textContent = 'You clicked it!';
4});
Terminal
Every line, explained
<!doctype html>
<!doctype html> is the very first line of every real web page. It simply tells the browser "this is a modern HTML page"; it is a declaration, not a tag, so it never gets closed.
<html>
<html> is the root: every other tag on the page lives inside it. Intro to HTML skipped this wrapper; now you are writing pages the way the pros do.
<head>
<head> holds information ABOUT the page: its title, and links to other files. Nothing inside <head> is drawn on the page itself.
<title>Clicks</title>
<title> names the browser tab. Look at the tab bar of a real browser: every name you see there is one of these.
</head>
</head> closes the head. The visible part of the page comes next.
<body>
<body> holds everything you can actually see: all the tags you learned in Intro to HTML go in here.
<h1 id="greeting">Hello!</h1>
The named heading again.
<button id="magic">Click me</button>
The button gets an id too, so the script can find it.
<script src="script.js"></script>
<script src="script.js"></script> loads the JavaScript file. It sits at the END of the body so the page above it exists before the script runs; a script that looks for a tag that hasn't been built yet finds nothing.
</body>
</body> closes the body.
</html>
</html> closes the root tag. Nothing comes after it.
const btn = document.getElementById('magic');
document is JavaScript's handle on the page, and getElementById fetches ONE tag by its id attribute. This is the bridge between the files: HTML gives a tag a name, JavaScript grabs it by that name.
btn.addEventListener('click', () => {
addEventListener tells the button: "when this event happens, run this function". The event is 'click', and the function is an arrow function, just like the ones in Intro to JavaScript. Nothing runs yet; it waits.
document.getElementById('greeting').textContent = 'You clicked it!';
The waiting code: find the heading, change its text. It runs every time the button is clicked.
});
The } closes the arrow function and the ) closes addEventListener. Run the page and click the button: THAT is the moment HTML, attributes and JavaScript click together (pun intended).