Unit 5: Interactive Web Development

CSE326 — Internet Programming 6 min read

I. Orientation

Interactive web development centres on JavaScript's ability to respond to user actions, manipulate the browser environment, and communicate with external services in real time (standardised through W3C and WHATWG specifications). The browser exposes a layered API surface — the DOM, Web Storage, Fetch, Geolocation, and others — that JavaScript programs against to produce dynamic, stateful experiences without full page reloads.

  • Client-side execution: JavaScript runs in the browser, enabling immediate feedback without server round-trips.
  • Event-driven model: code executes in response to user or system events rather than sequentially from start to finish.
  • API surface: standardised browser interfaces abstract platform differences and provide consistent access to device capabilities.
  • Accessibility obligation: every interactive feature must remain operable for users relying on keyboards and assistive technologies.

II. JavaScript Core Concepts

JavaScript's iterative and functional constructs underpin all interactive logic on the page.

A. Loops and Iterative Programming

Loops repeat a block of code for a known or unknown number of iterations.

  • for loop: counter-driven — for (let i = 0; i < arr.length; i++).
  • for...of: iterates over iterable values (arrays, strings, NodeLists) — for (const item of items).
  • while / do...while: condition-driven; do...while guarantees at least one execution.
  • Array iteration methods: forEach, map, filter, reduce replace explicit loops for array processing and avoid index management errors.

B. Higher Order Functions

A higher-order function (HOF) takes a function as an argument or returns one, enabling abstraction over behaviour.

  • map(fn): transforms each element — [1,2,3].map(x => x * 2)[2,4,6].
  • filter(fn): retains elements where fn returns true.
  • reduce(fn, init): accumulates a single value — [1,2,3].reduce((acc,x) => acc+x, 0)6.
  • Returning functions: closures produced by HOFs capture outer scope, enabling factories and partial application.

C. Callback Functions

A callback is a function passed as an argument to be invoked later, either synchronously or asynchronously.

  • Synchronous callback: arr.sort((a, b) => a - b) — called immediately inside sort.
  • Asynchronous callback: setTimeout(() => console.log('done'), 1000) — called after a delay.
  • Callback hell: deeply nested callbacks reduce readability; Promises and async/await are the modern alternative.

III. Document Object Model

The DOM is the browser's in-memory tree representation of an HTML document, traversable and mutable via JavaScript.

A. DOM Fundamentals

The DOM models every HTML element as a node in a tree rooted at document.

  • Node types: Element, Text, Comment, Document — most manipulation targets Element nodes.
  • Tree relationships: parentNode, childNodes, firstChild, nextSibling traverse the hierarchy.
  • Live vs. static collections: getElementsByTagName returns a live HTMLCollection; querySelectorAll returns a static NodeList.

B. DOM Selection and Manipulation

Selection retrieves nodes; manipulation changes their content, attributes, or position in the tree.

  • Selection methods:
    • document.getElementById('id') — single element by id.
    • document.querySelector('css') — first match for any CSS selector.
    • document.querySelectorAll('css') — all matches as a static NodeList.
  • Content: element.textContent (plain text); element.innerHTML (HTML string — sanitise before use to prevent XSS).
  • Attributes: element.setAttribute('class','active'), element.classList.add/remove/toggle.
  • Creating and inserting: document.createElement('div'), then parent.appendChild(node) or parent.insertBefore(node, ref).
  • Removing: element.remove().

IV. User Interaction

A. Event Handling

Events are signals fired by the browser when the user or system performs an action.

  • Registering listeners: element.addEventListener('click', handler) — preferred over inline onclick.
  • Event object: the handler receives an Event; event.target is the element that fired it.
  • Propagation: events bubble up the DOM by default; event.stopPropagation() halts bubbling; event.preventDefault() cancels the default browser action (e.g., form submission).
  • Event delegation: attach one listener to a parent and inspect event.target to handle events from many children efficiently.

B. Dynamic Content Generation

Dynamic content is created or updated in the DOM at runtime without a page reload.

  • Template literals: `<li>${item.name}</li>` compose HTML strings cleanly.
  • innerHTML injection: fast but risks XSS; always sanitise user-supplied data before insertion.
  • createElement + appendChild: safer programmatic approach for building node trees.
  • DocumentFragment: batch-inserts multiple nodes in one DOM operation to minimise reflows.

C. JavaScript Accessibility Practices

Accessible interactive content ensures keyboard and screen-reader users receive equivalent experiences.

  • ARIA attributes: aria-label, aria-expanded, aria-live communicate dynamic state — e.g., btn.setAttribute('aria-expanded','true').
  • Focus management: after dynamic content changes, call element.focus() so screen readers announce new content.
  • Keyboard events: supplement click with keydown handlers for Enter and Space on custom interactive elements.
  • Semantic HTML first: native elements (<button>, <input>) carry built-in accessibility; use ARIA only to supplement, not replace.

V. Data Input and Validation

A. Form Validation

Validation checks user input before submission, providing immediate feedback without a server round-trip.

  • HTML5 built-in: required, type="email", minlength, pattern trigger browser validation without JavaScript.
  • Constraint Validation API: input.validity.valid (boolean), input.setCustomValidity('message') allow programmatic checks.
  • Custom validation: listen for submit, call event.preventDefault(), inspect field values, and display errors in associated <span> elements.
  • Client vs. server: client-side validation improves UX; server-side validation is mandatory for security.

B. Regular Expressions

A regular expression (regex) is a pattern used to match, search, or replace text.

  • Literal syntax: /pattern/flags — e.g., /^\d{3}-\d{4}$/ matches a phone segment.
  • Key methods: regex.test(str) → boolean; str.match(regex) → array of matches; str.replace(regex, fn).
  • Common flags: g (global), i (case-insensitive), m (multiline).
  • Validation use: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) — basic email format check.

VI. Browser APIs

A. Date and Time Handling

The Date object provides creation, parsing, and formatting of dates and times.

  • Creating: new Date() (now), new Date('2024-06-01'), new Date(year, month, day) — month is 0-indexed.
  • Key methods: getFullYear(), getMonth(), getDate(), getTime() (ms since epoch).
  • Formatting: date.toLocaleDateString('en-GB') uses locale conventions; Intl.DateTimeFormat gives fine-grained control.
  • Arithmetic: subtract two Date objects for milliseconds; divide by 86400000 for days.

B. Audio and Video Events

The HTMLMediaElement interface exposes events for controlling media playback programmatically.

  • Key events: play, pause, ended, timeupdate (fires as position changes), loadedmetadata (duration available).
  • Programmatic control: video.play(), video.pause(), video.currentTime = 30 (seek to 30 s).
  • Custom controls: listen to timeupdate to update a progress bar; listen to ended to show a replay button.

C. Browser Storage using Web Storage API (Local Storage and Session Storage)

Web Storage provides synchronous key-value storage in the browser wi