JavaScript Basics

JavaScript adds behavior to a page: things that happen when someone clicks, types, or loads the page. HTML gives a page structure, CSS gives it style, and JavaScript gives it something to do.

Adding a script

Link a JavaScript file near the end of <body>, after the rest of the page, so it doesn’t try to run before the page exists:

<script src="script.js"></script>

Variables

A variable stores a value so you can use it again later. Use let for a value that might change, and const for one that won’t:

let count = 0;
const name = "Mindy";

Functions

A function is a reusable block of code. Define it once, then call it by name whenever you need it:

function greet(name) {
  console.log("Hello, " + name);
}

greet("Mindy");

Responding to clicks

To make something happen on a click, first find the element with querySelector, then attach a listener to it:

const button = document.querySelector("#my-button");

button.addEventListener("click", function () {
  alert("Button clicked!");
});

The same pattern works for typing, scrolling, hovering, or loading the page, just by swapping out "click" for a different event name.

Try it: add a bit of interactivity

Back to the profile page from the HTML and CSS guides: here’s how to add a button that reveals a fun fact when clicked.

1. Add a button and a hidden paragraph to the HTML, right after the hobbies list:

<button id="fact-button">Show a fun fact</button>
<p id="fun-fact" hidden>I once baked 12 loaves of sourdough in one weekend.</p>

The hidden attribute is a plain HTML attribute (see the HTML basics guide) that hides an element until something removes it.

2. Select both elements and listen for a click, in script.js:

const button = document.querySelector("#fact-button");
const fact = document.querySelector("#fun-fact");

button.addEventListener("click", function () {
  fact.hidden = false;
});

Clicking the button now sets fact.hidden to false, which makes the paragraph appear. That’s the whole pattern most page interactivity comes down to: select an element, listen for an event, change something in response.

The local-only guide covers how JavaScript can read and work with a file a visitor picks, entirely in their own browser, and the mortgage calculator guide puts variables, functions, and a form together into one working example.

← back to guides