Unit 5: Interactive Web Development
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.
forloop: 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...whileguarantees at least one execution.- Array iteration methods:
forEach,map,filter,reducereplace 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 wherefnreturnstrue.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 insidesort. - Asynchronous callback:
setTimeout(() => console.log('done'), 1000)— called after a delay. - Callback hell: deeply nested callbacks reduce readability; Promises and
async/awaitare 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 targetsElementnodes. - Tree relationships:
parentNode,childNodes,firstChild,nextSiblingtraverse the hierarchy. - Live vs. static collections:
getElementsByTagNamereturns a liveHTMLCollection;querySelectorAllreturns a staticNodeList.
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'), thenparent.appendChild(node)orparent.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 inlineonclick. - Event object: the handler receives an
Event;event.targetis 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.targetto 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. innerHTMLinjection: 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-livecommunicate 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
clickwithkeydownhandlers forEnterandSpaceon 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,patterntrigger browser validation without JavaScript. - Constraint Validation API:
input.validity.valid(boolean),input.setCustomValidity('message')allow programmatic checks. - Custom validation: listen for
submit, callevent.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.DateTimeFormatgives fine-grained control. - Arithmetic: subtract two
Dateobjects for milliseconds; divide by86400000for 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
timeupdateto update a progress bar; listen toendedto 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
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →