💻 Topic 21: Programming for the Web (JavaScript)

Welcome to the final topic of your A Level IT journey! This chapter is incredibly practical and exciting, focusing on how we make websites *do* things. Up until now, you might have used HTML to structure a page and CSS to make it look beautiful. But it’s JavaScript (JS) that gives the web page a brain and allows it to interact with the user.

Prerequisite Knowledge: We assume you have a good understanding of HTML (structure) and CSS (styling), as covered in earlier qualifications like IGCSE Website Authoring.

Let’s dive into how you can use JavaScript to bring your web pages to life!


21.1 Using JavaScript to Add Interactivity

JavaScript is a high-level, interpreted scripting language used primarily on the client side (in the user's web browser). It allows you to change the content, style, and behaviour of a web page dynamically after it has loaded.

Methods of Inserting JavaScript

You can add JS code to your HTML document in two main ways:

  1. Inserting JavaScript in HTML (Internal Script):
    You place the code directly within the HTML using the <script> tags, usually in the <head> or just before the closing </body> tag. This is suitable for small, specific scripts.
  2. Creating and using External Scripts:
    You write the JS code in a separate file (e.g., script.js) and link it to the HTML using the <script src="script.js"></script> tag. This is best practice for large projects, as it makes the code easier to organise, maintain, and reuse.

Key Takeaway: Separating JS into external files keeps your HTML clean and improves page loading speed (as the script can be cached by the browser).

Manipulating HTML Content and Styles (The DOM)

To change anything on a web page, JavaScript interacts with the Document Object Model (DOM). Think of the DOM as a tree structure representing all the elements on the page.

To manipulate an element, you first need to target it. The most common way to target a single element is using its ID:

document.getElementById(id)

Once targeted, you can change its:

  1. Text/Number Content:
    Use the innerHTML property to insert or change text or numerical values within the targeted element.
  2. Example: document.getElementById("greeting").innerHTML = "Hello World!";

  3. Calculations and String Manipulation:
    JS can perform calculations and then display the result. It can also perform string manipulation, such as joining text (`concatenation`).
  4. Example: document.getElementById("output").innerHTML = 5 + 7;

  5. Styles (CSS Properties):
    You can change the style of an element by accessing its style object and modifying a CSS property (written in camelCase, e.g., backgroundColor).
  6. Syntax: document.getElementById(id).style.property = new style

    Example: document.getElementById("btn1").style.color = "red";

  7. Images and Image Properties:
    You can change the source (`src`) or size of an image element dynamically.
  8. Example: document.getElementById("photo").src = "new_image.jpg";

Showing and Hiding HTML Elements

This is a fundamental aspect of interactivity, often used for menus, popups, or expanding information.

  • Using style.visibility:
    Setting .style.visibility = "hidden" hides the element, but it still occupies the original space on the page.
  • Using style.display:
    Setting .style.display = "none" hides the element entirely, and the space it occupied is reclaimed by other elements on the page.
✅ Quick Review: Visibility vs. Display

Visibility: Hides it, but holds the space (like an invisible chair).

Display: Hides it and removes it from the layout flow (like removing the chair completely). This is usually the preferred method for making things disappear.


Displaying Data and User Interaction

JavaScript provides several built-in methods for displaying output and soliciting input from the user.

Displaying Data in Different Ways
  1. Writing into an HTML element (using innerHTML):
    (Covered above) This is the standard, user-friendly way to display data within the page structure.
  2. Writing into the HTML output (using document.write()):
    This writes directly to the document stream. Warning: If executed *after* the page has fully loaded (e.g., inside an event), it usually overwrites the entire existing document, deleting all current content! Use sparingly.
  3. An Alert Box (using window.alert()):
    This displays a small modal box with a message and an "OK" button. It stops the program execution until the user clicks OK.
  4. Example: window.alert("Data submitted successfully!");

  5. The Browser Console (using console.log()):
    This writes output to the browser's developer console. This method is crucial for debugging—it allows programmers to check variable values and confirm if code blocks are running without disrupting the visible web page.
User Interaction Popups

These pop-ups allow simple data collection and decision-making from the user.

  • confirm(): Displays a dialog box with a message and two buttons: "OK" and "Cancel". It returns a Boolean value (true if OK is clicked, false if Cancel is clicked).
  • Analogy: Asking, "Are you sure you want to proceed?" (Yes/No).

  • prompt(): Displays a dialog box asking the user to input a value. It returns the user's input as a string, or null if they press Cancel.
  • Analogy: Asking, "What is your name?" (A text input box).


Reacting to Common HTML Events

The web is event-driven. This means the JavaScript code only runs when a specific action (an event) occurs. You must be able to recognise and use the following common HTML events:

  • onload: Triggered when an object (like the entire page or an image) has finished loading. Use: Ensuring all page elements are ready before running a script.
  • onchange: Triggered when an element's value is changed (often used with input fields or drop-down menus).
  • onclick: Triggered when the user clicks an element (most common event for buttons).
  • onmouseover: Triggered when the mouse cursor moves over an element.
  • onmouseout: Triggered when the mouse cursor moves away from an element.
  • onkeydown: Triggered when a keyboard key is pressed down while an element (like an input field) has focus.

Did you know? Using events allows the web page to feel reactive and immediate, which is why JS is so essential for modern user experience.


The Structure and Syntax of JavaScript Code

To write functional JS, you must understand its basic building blocks.

JavaScript Statements

A JavaScript statement is an instruction to be executed by the web browser. Statements are separated by semicolons (;).

  • Values (Literals and Variables):
    Values are the data JS works with. Literals are fixed values (e.g., 10.5, "Text", true). Variables are used to store data values (e.g., let score = 50;).
  • Keywords:
    Words reserved by JS for specific functions (e.g., let, if, function, for). You cannot use keywords as variable names.
  • Expressions:
    A combination of values, variables, and operators that evaluates to a single value. Example: 5 * (x + 2)
Data Types and Type Conversions

You must understand the fundamental data types:

  • number: Used for integers and decimals.
  • string: Used for text (enclosed in quotes).
  • Boolean: Stores true or false.
  • array: Used to store multiple values in a single variable (e.g., let colours = ["red", "blue", "green"]).
  • object: Used to store collections of named values (e.g., let person = {name: "Ali", age: 18}).

Type Conversions: JavaScript is loosely typed, meaning variables can change type, and the interpreter often performs automatic type conversion (coercion). You should be aware of this, especially when performing mathematical operations on input data which might initially be read as a string.

Operators (The Calculators of JS)

Operators perform operations on values and variables.

  • Assignment Operators: Used to assign values to variables (e.g., x = 5, x += 2).
  • Arithmetic Operators: Standard math operations (+, -, *, /, % (modulus, remainder)).
  • Algebraic Operators: Similar to arithmetic, used in expressions.
  • String Operators: Primarily the addition operator (+) used for concatenation (joining strings).
  • Logical Operators: Used to determine the logic between variables or values.
    • AND (&&): True if both statements are true.
    • OR (||): True if at least one statement is true.
    • NOT (!): Reverses the logical state.
  • Comparison Operators (Logical, Conditional, Type): Used in conditional tests (e.g., in if statements or loops) to check equality or relationships.
    • == (Equal to): Compares value only. (Common Mistake: "5" == 5 is true)
    • === (Equal value and equal type): Compares value and type. ("5" === 5 is false)
    • != (Not equal to)
    • !== (Not equal value or not equal type)
    • > (Greater than), < (Less than), >= (Greater than or equal to), <= (Less than or equal to)
⚠ Common Mistake Alert

Always use === (triple equals) in JavaScript unless you specifically intend to ignore the data type. Triple equals prevents unexpected behaviour caused by automatic type conversion!


Control Flow, Functions, and Timing

For a program to be useful, it needs to make decisions and repeat actions.

Conditional Operators and Flow Control

These operators allow code blocks to execute based on whether a condition is true or false.

  • if, else, else if: Used for decision-making. JS also supports the Ternary operator (a shortcut for simple if...else statements).
  • Example: if (score >= 90) { grade = 'A'; } else { grade = 'B'; }

  • switch: Used when testing a variable against many different possible values (cases).
JavaScript Loops for Iterative Methods

Loops allow a block of code to be executed repeatedly (iterated).

  1. for loop: Used when you know exactly how many times you want to repeat the code.

    Structure: for (initialisation; condition; increment) { code... }

  2. for/in loop: Used to loop through the properties of an Object.
  3. while loop: Used when the number of iterations is not known; the loop continues as long as a specified condition is true.
  4. do/while loop: Similar to the while loop, but the code block is executed at least once before the condition is tested.

The break statement can be used inside any loop or switch block to immediately exit that structure.

Functions

A function is a block of code designed to perform a particular task. Functions are fundamental to structured programming and avoid code repetition.

Functions can be executed in three ways:

  1. When an event occurs (e.g., onclick).
  2. When invoked (called) from other code (e.g., another function calls it).
  3. Automatically (self-invoked) when the page loads, usually if the function is defined and immediately executed within brackets.
JavaScript Timing Events

Timing events allow you to schedule the execution of functions over time, adding a sense of responsiveness or delayed effects.

  • setTimeout(): Executes a function once after a specified number of milliseconds (ms).

    Use: Displaying a "Thank you" message 3 seconds after a form submission.

  • setInterval(): Executes a function repeatedly, starting after a specified interval (ms).

    Use: Creating a clock that updates every 1000ms (1 second).


Annotating JavaScript Code

Comments are non-executable text added to code to explain its purpose or function. They are vital for readability, especially when working in a team or reviewing your own code later.

  • Single-line comment: Starts with //
  • Multi-line comment: Starts with /* and ends with */

🚀 Key Takeaway for Practical Work (Paper 4)

In Paper 4, you will often need to write a function that performs a calculation, modifies an element's style or content using document.getElementById(), and then link that function to a user event like onclick or onchange. Practise this sequence until it is second nature!