Use JavaScript for web interactivity

Programming for the Web – Using JavaScript for Interactivity

1. Why JavaScript?

  • De‑facto client‑side language for adding interactivity to web pages.
  • Runs directly in the browser – no compilation step, instant response to user actions.
  • Can read, modify and create HTML/CSS (the Document Object Model – DOM) without reloading the page.
  • Supported by all modern browsers and increasingly used on the server (Node.js) and in emerging web‑based technologies (Web‑AR, IoT dashboards).

2. Ways to Include JavaScript in a Web Page

Method Syntax Typical Use Key Points
Inline <button onclick="myFunction()">Click</button> Very small scripts or quick prototypes Mixes markup with behaviour → hard to maintain.
Internal (in‑page) <script>function myFunction(){…}</script> Page‑specific code, easy debugging Still mixes structure and behaviour; not cached by the browser.
External <script src="script.js"></script> Reusable code, separation of concerns, browser caching Recommended for production sites.
ES6 Module <script type="module" src="main.mjs"></script> Modern projects that need import/export of functions/objects Modules are loaded with defer semantics, have their own scope and can import other modules.

3. Event‑Driven Programming

JavaScript reacts to events such as clicks, key presses, page loads, or network responses. The typical pattern is:

  1. Select the element (e.g. document.getElementById('btn')).
  2. Attach an event listener (addEventListener('click', handler)).
  3. Define the handler function that performs the required action.

3.1 The Event Object & Propagation

  • event.type – name of the event (e.g. click).
  • event.target – element that originally triggered the event.
  • event.currentTarget – element the listener is attached to.
  • event.preventDefault() – stops the default browser action (e.g. following a link).
  • event.stopPropagation() – stops further bubbling/capturing.
  • Propagation phases:
    • Capturing – from the document root down to the target.
    • Bubbling – from the target back up to the root.

3.2 Example – Click with Capture & Bubble Phases

<button id="outer">
    Outer
    <span id="inner">Inner</span>
</button>

<script>
    const outer = document.getElementById('outer');
    const inner = document.getElementById('inner');

    // Capture phase (third argument true)
    outer.addEventListener('click', e => {
        console.log('Outer – capture');
    }, true);

    // Bubble phase (default)
    outer.addEventListener('click', e => {
        console.log('Outer – bubble');
    });

    inner.addEventListener('click', e => {
        console.log('Inner – bubble');
        // e.stopPropagation(); // uncomment to stop bubbling
    });
</script>

4. Manipulating the DOM

4.1 Selecting Elements

  • document.getElementById(id) – returns a single element, fastest lookup.
  • document.querySelector(selector) – returns the first element that matches a CSS selector.
  • document.querySelectorAll(selector) – returns a static NodeList of all matches.

4.2 Updating Content – Performance‑Friendly Options

Method What it changes Performance impact
textContent Plain text inside an element Low – no HTML parsing, minimal re‑flow.
innerHTML HTML markup inside an element Higher – parses HTML, may cause re‑flow.
insertAdjacentHTML(position, html) Inserts HTML at a specific position (beforebegin, afterbegin, beforeend, afterend) More efficient than setting innerHTML on large containers.
element.append(...nodes) / element.prepend(...nodes) Inserts DOM nodes (no HTML parsing) Fast – works with existing nodes.

4.3 Styling & Class Manipulation

  • Inline style: element.style.property = 'value'
  • Class list API:
    • element.classList.add('active')
    • element.classList.remove('active')
    • element.classList.toggle('active')
  • Prefer class changes over direct style changes for maintainability and to keep design logic in CSS.

4.4 Example – Adding Items to a To‑Do List

<ul id="tasks"></ul>
<input id="newTask" placeholder="Add a task">
<button id="addBtn">Add</button>

<script>
    const list = document.getElementById('tasks');
    const input = document.getElementById('newTask');
    const btn = document.getElementById('addBtn');

    btn.addEventListener('click', () => {
        const text = input.value.trim();
        if (!text) return;                     // simple validation

        const li = document.createElement('li');
        li.textContent = text;
        li.classList.add('task-item');
        list.appendChild(li);
        input.value = '';
    });
</script>

5. Modern JavaScript Features for Interactivity

  • let / const – block‑scoped variables; avoid the pitfalls of var.
  • Arrow functions – concise syntax; lexical this.
  • Template literals – easier string interpolation (`Hello ${name}`).
  • Destructuring – extract values from objects or arrays.
  • Async / await – readable asynchronous code (e.g., fetching data).
  • ES6 Modulesexport / import to organise code.

5.1 Example – A Simple Quiz Helper as an ES6 Module

// quizHelper.mjs
export const questions = [
    { q: 'Capital of France?', a: 'Paris' },
    { q: '2 + 2 = ?', a: '4' }
];

export function checkAnswer(user, correct) {
    return user.trim().toLowerCase() === correct.toLowerCase();
}
// main.mjs
import { questions, checkAnswer } from './quizHelper.mjs';

const feedback = document.getElementById('feedback');
document.getElementById('checkBtn').addEventListener('click', () => {
    const user = document.getElementById('answer').value;
    const correct = questions[0].a;
    feedback.textContent = checkAnswer(user, correct) ? 'Correct!' : 'Wrong';
});

6. Server‑Side Basics & Web‑Server Fundamentals (Cambridge AO2/AO3)

6.1 Why a Server‑Side Component?

  • Stores data persistently (e.g., user accounts, quiz results).
  • Performs operations that must not be exposed to the client (validation, authentication).
  • Provides APIs that JavaScript can call via fetch or XMLHttpRequest.

6.2 Node.js Overview

  • JavaScript runtime built on Chrome’s V8 engine.
  • Runs outside the browser – ideal for lightweight back‑ends.
  • Uses the http module to create a server that listens for requests and sends responses.

6.3 Simple CRUD Example (Node.js + Express)

// server.js (run with: node server.js)
const express = require('express');
const app = express();
app.use(express.json());               // parse JSON bodies

let tasks = [];                         // in‑memory store

// Create
app.post('/api/tasks', (req, res) => {
    const { text } = req.body;
    if (!text) return res.status(400).json({ error: 'Missing text' });
    const id = Date.now();
    tasks.push({ id, text });
    res.status(201).json({ id, text });
});

// Read
app.get('/api/tasks', (req, res) => {
    res.json(tasks);
});

// Update
app.put('/api/tasks/:id', (req, res) => {
    const task = tasks.find(t => t.id == req.params.id);
    if (!task) return res.status(404).json({ error: 'Not found' });
    task.text = req.body.text || task.text;
    res.json(task);
});

// Delete
app.delete('/api/tasks/:id', (req, res) => {
    tasks = tasks.filter(t => t.id != req.params.id);
    res.status(204).end();
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));

6.4 Consuming the API from the Front End

// client.js (included as a module)
async function loadTasks() {
    const resp = await fetch('/api/tasks');
    const data = await resp.json();
    // render data …
}

6.5 Mapping to Cambridge AO2/AO3

  • AO2 – Design & Development: design API endpoints, choose data structures, write server‑side code.
  • AO3 – Testing & Evaluation: unit‑test server routes, use Postman or browser dev tools, evaluate security and performance.

7. Using External Libraries (Conceptual Overview)

Library / Framework Typical Use in A‑Level Projects Key Learning Point
jQuery Simplifies DOM selection, event handling and AJAX. Understanding abstraction over native APIs.
Chart.js Creates responsive charts for data visualisation. Integrates JavaScript with the <canvas> element.
D3.js Advanced data‑driven visualisations (e.g., interactive maps). Shows binding of data to DOM/SVG.
React / Vue (conceptual) Component‑based UI design; useful for discussing modern web development. Highlights the shift from imperative DOM manipulation to declarative UI.

8. Responsive Design & CSS Integration

  • Add the viewport meta tag: <meta name="viewport" content="width=device-width, initial-scale=1">
  • Use CSS media queries to adapt layout for different screen sizes.
  • JavaScript can toggle CSS classes to switch between mobile and desktop states.

Example – Toggling a Mobile Navigation Menu

<button id="menuBtn">Menu</button>
<nav id="mainNav" class="nav">…</nav>

<style>
    .nav { display: none; }
    .nav.open { display: block; }
    @media (min-width: 768px) {
        .nav { display: block !important; }
    }
</style>

<script>
    const btn = document.getElementById('menuBtn');
    const nav = document.getElementById('mainNav');

    btn.addEventListener('click', () => nav.classList.toggle('open'));
</script>

9. Accessibility (A‑Level Requirement)

  • Use semantic HTML elements (<button>, <nav>, <form>) so assistive technologies can identify them.
  • Provide aria-label, aria-expanded or role attributes for custom widgets.
  • Ensure all functionality is reachable via keyboard (e.g., keydown events, tabindex="0" for non‑interactive elements).
  • Maintain a contrast ratio of at least 4.5:1 for normal text; avoid conveying meaning by colour alone.

10. Web Security Essentials (e‑Security)

Threat Typical Attack Vector Mitigation in JavaScript
Cross‑Site Scripting (XSS) Injecting malicious HTML/JS via user input. Sanitise/escape all data before inserting into the DOM; prefer textContent over innerHTML.
Cross‑Site Request Forgery (CSRF) Tricking a logged‑in user into sending unwanted requests. Include anti‑CSRF tokens in POST requests; set SameSite attribute on cookies.
Insecure Direct Object References (IDOR) Manipulating URLs or parameters to access unauthorised data. Never rely solely on client‑side checks; validate all inputs on the server.
Content Security Policy (CSP) Browser‑enforced policy that restricts sources of scripts, styles, etc. Set a CSP header (e.g., Content‑Security‑Policy: script-src 'self') on the server.

Security Checklist for Client‑Side Code

  1. Escape user‑generated content before using innerHTML.
  2. Prefer textContent or DOM‑creation methods (createElement) over HTML strings.
  3. Validate form data client‑side for usability, but always re‑validate server‑side.
  4. Make all network requests over HTTPS.
  5. Configure appropriate CSP headers on the server.
  6. Never store passwords or sensitive tokens in localStorage or sessionStorage.

11. Networking Basics for Web Applications

  • HTTP / HTTPS – request/response protocol used by browsers. HTTPS adds TLS encryption.
  • RESTful APIs – expose data via endpoints using standard methods: GET (read), POST (create), PUT/PATCH (update), DELETE (remove).
  • Fetch API – modern promise‑based way to perform asynchronous network requests.
    fetch('https://api.example.com/items')
        .then(r => {
            if (!r.ok) throw new Error('Network error');
            return r.json();
        })
        .then(data => {
            // use data …
        })
        .catch(err => console.error(err));
    
  • JSON – lightweight data‑interchange format; JSON.stringify() and JSON.parse() convert between objects and text.

Example – Fetching JSON Data and Rendering a Chart (Chart.js)

<canvas id="myChart" width="400" height="200"></canvas>

<script type="module">
    import Chart from 'https://cdn.jsdelivr.net/npm/chart.js';

    async function loadSales() {
        const resp = await fetch('https://api.example.com/sales');
        if (!resp.ok) throw new Error('Failed to load data');
        return resp.json(); // expects [{ month:'Jan', value:120 }, …]
    }

    loadSales().then(data => {
        const ctx = document.getElementById('myChart').getContext('2d');
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.map(d => d.month),
                datasets: [{
                    label: 'Sales',
                    data: data.map(d => d.value),
                    borderColor: 'steelblue',
                    fill: false
                }]
            }
        });
    });
</script>

12. Web Development Life‑Cycle (Cambridge AO2/AO3)

  1. Requirements gathering – define functionality, user stories, and accessibility/security needs.
  2. Design – create wire‑frames, data models, and decide on client‑/server‑side division.
  3. Implementation
    • Write HTML/CSS (structure & presentation).
    • Write JavaScript for interactivity (event handling, DOM updates, API calls).
    • Develop server‑side code (Node/Express, REST endpoints).
  4. Testing
    • Unit testing of functions (Jest, Mocha).
    • Integration testing of API calls (Postman, fetch mock).
    • Usability testing – check keyboard navigation, colour contrast, screen‑reader behaviour.
    • Security testing – attempt XSS injection, verify CSP.
  5. Deployment – upload static files to a web host, deploy server code to a platform (e.g., Heroku, Render), configure HTTPS and CSP headers.
  6. Maintenance – monitor performance, apply security patches, add new features based on user feedback.

Each stage maps directly to assessment objectives:

  • AO1 – knowledge of concepts (HTML, CSS, JavaScript, HTTP, security).
  • AO2 – application of knowledge in design and development (writing code, creating APIs).
  • AO3 – evaluation and testing (debugging, security checks, performance optimisation).

13. Testing & Debugging Tools

  • Browser DevTools – Elements panel (inspect DOM), Console (log output, view errors), Network (view HTTP requests), Sources (set breakpoints).
  • Linting – ESLint enforces coding standards and catches common mistakes.
  • Automated testing – Jest or Mocha for unit tests; Cypress for end‑to‑end testing of UI interactions.
  • Performance profiling – Chrome’s Performance tab to identify re‑flows, long‑running scripts, and memory leaks.

Create an account or Login to take a Quiz

44 views
0 improvement suggestions

Log in to suggest improvements to this note.