JavaScript — Making Web Pages Interactive
JavaScript is what makes the web come alive. This guide covers the basics you need to start adding real interactivity to your pages — no frameworks, no Node.js, just pure browser JavaScript.
What Does JavaScript Do on a Webpage?
HTML gives a page structure. CSS gives it style. JavaScript gives it behaviour. It's the only programming language that runs directly inside a web browser, and it can do things HTML and CSS simply can't:
- Respond to user actions — button clicks, key presses, form submissions
- Change page content without reloading (show/hide elements, update text)
- Validate forms and give instant feedback
- Fetch data from servers and display it dynamically
- Store information locally in the browser (localStorage)
- Animate elements and create interactive experiences
JavaScript runs in the browser — no installation needed by your visitors. You add it to a page with a <script> tag at the bottom of the <body>, or in an external .js file linked with the src attribute.
<!-- Inline (small scripts only) --><script> console.log('Hello from JavaScript!');</script><!-- External file (preferred — keeps HTML clean) --><!-- Place at bottom of body or use defer attribute --><script src="script.js"defer></script>Variables
Variables store values so you can use and reuse them. Use const for values that won't change, and let for values that will. Avoid var — it's the old way and has confusing behaviour.
// const — value cannot be reassignedconst siteName = 'Webgrade EDU';const maxItems = 10;const isPublished = true;// let — value can changelet count = 0;count = count + 1; // now count is 1count++; // shorthand — now count is 2// Data typesconst name = 'Alice'; // string (text)const age = 25; // numberconst active = true; // boolean (true/false)const items = ['a', 'b', 'c']; // arrayconst user = { name: 'Alice', age: 25 }; // object// Template literals — embed variables in stringsconst greeting = `Hello, ${name}! You are ${age} years old.`;Functions
A function is a reusable block of code that runs when called. Functions are one of the most important building blocks in programming — they let you organise code, avoid repetition, and build logic.
// Function declarationfunctiongreet(name) { return`Hello, ${name}!`;}greet('Alice'); // returns "Hello, Alice!"// Arrow function (modern, shorter syntax)constdouble = (num) => num * 2;double(5); // returns 10// Function with multiple linesconstformatPrice = (price) => { const rounded = price.toFixed(2); return`£${rounded}`;};formatPrice(9.9); // returns "£9.90"// Calling functions on events (covered next)functionshowAlert() { alert('Button clicked!');}Events
Events are things that happen in the browser — a user clicks a button, moves the mouse, submits a form, or scrolls the page. JavaScript can "listen" for these events and run code in response.
The modern way to attach event listeners is with addEventListener. Avoid inline event handlers in HTML (onclick="...") — they mix JavaScript into your HTML and are harder to manage.
// Get a reference to the buttonconst btn = document.getElementById('myButton');// Listen for a click and run a functionbtn.addEventListener('click', function() { alert('You clicked the button!');});// Arrow function syntax (same result)btn.addEventListener('click', () => { console.log('Clicked!');});// Common event typesbtn.addEventListener('click', handler); // mouse clickinput.addEventListener('input', handler); // text typedform.addEventListener('submit', handler); // form submittedwindow.addEventListener('scroll', handler); // page scrolledimg.addEventListener('load', handler); // image loaded// Preventing default browser behaviourform.addEventListener('submit', (e) => { e.preventDefault(); // stop page from reloading// now handle submission with JS});DOM Manipulation
The DOM (Document Object Model) is the browser's representation of your HTML as a tree of objects. JavaScript can read and change the DOM — adding, removing, and modifying elements dynamically without reloading the page.
// Select elementsconst el = document.getElementById('myId'); // by idconst first = document.querySelector('.card'); // first matchconst all = document.querySelectorAll('.card'); // all matches (NodeList)const links = document.querySelectorAll('nav a'); // CSS selector syntaxconst heading = document.querySelector('h1');// Change textheading.textContent = 'New Heading Text';// Change HTML (allows tags)heading.innerHTML = '<em>Italic</em> heading';// Change stylesheading.style.color = '#2d6aff';// Add/remove/toggle CSS classesheading.classList.add('highlight');heading.classList.remove('highlight');heading.classList.toggle('active'); // add if absent, remove if present// Change attributesconst img = document.querySelector('img');img.setAttribute('src', 'new-photo.jpg');img.setAttribute('alt', 'Updated description');const hamburger = document.getElementById('hamburger');const menu = document.getElementById('mobileMenu');hamburger.addEventListener('click', () => { // Toggle 'open' class on both the button and menu hamburger.classList.toggle('open'); menu.classList.toggle('open');});// Close menu when clicking outsidedocument.addEventListener('click', (e) => { if (!hamburger.contains(e.target) && !menu.contains(e.target)) { hamburger.classList.remove('open'); menu.classList.remove('open'); }});Working with Lists of Elements
const cards = document.querySelectorAll('.card');// Loop through all cards and add a click listenercards.forEach((card) => { card.addEventListener('click', () => { card.classList.add('selected'); });});