Line At A Time
Lesson 9: Night Mode
Night Mode Use all three files at once: a button that restyles the page.
index.html
1<!doctype html>
2<html>
3 <head>
4 <title>Night Mode</title>
5 <link rel="stylesheet" href="style.css">
6 </head>
7 <body>
8 <h1>My Site</h1>
9 <button id="night">Night mode</button>
10 <script src="script.js"></script>
11 </body>
12</html>
style.css
1.night {
2 background-color: black;
3 color: white;
4}
script.js
1const nightBtn = document.getElementById('night');
2nightBtn.addEventListener('click', () => {
3 document.body.classList.toggle('night');
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>Night Mode</title>
<title> names the browser tab. Look at the tab bar of a real browser: every name you see there is one of these.
<link rel="stylesheet" href="style.css">
This line connects the stylesheet: rel="stylesheet" says what the file IS, href="style.css" says where it lives. From now on, everything in style.css shapes how this page looks. One page, two files, working together.
</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.
<button id="night">Night mode</button>
The switch.
<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.
.night {
A class rule, but notice: NOTHING in the HTML file wears this class. It sits waiting for JavaScript to hand it out.
color: white;
White text on black: night mode.
}
The } closes the rule.
const nightBtn = document.getElementById('night');
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.
nightBtn.addEventListener('click', () => {
A click listener, like last lesson.
document.body.classList.toggle('night');
The star of the show: classList is a tag's set of class labels, and toggle adds the class if it is missing and removes it if it is there. One line, and the button now switches night mode on AND off. JavaScript flips the label; CSS does the restyling. All three files, one team.
});
Close the function and the listener. Run it and click: lights off, lights on.