Information Communication Technology  ·  Level 6
Website Application
Chapter 3: Develop website application
📚 3 Topics

3.1 Creation of web pages

A web page is a document that a browser such as Chrome or Firefox downloads from a web server and displays. Three technologies build almost every page you have ever seen: HTML gives the page its structure and content, CSS controls how it looks, and JavaScript makes it respond to the user. A county government that puts its tender notices online, a SACCO that lets members check their share balance, and a hotel in Mombasa that takes room bookings all depend on these three layers working together. This topic teaches each layer in turn and shows how they combine into a working page.

3.1.1 HTML Coding

HTML (HyperText Markup Language) is the language used to describe the structure of a web page. It is not a programming language, because it makes no decisions and performs no calculations. Instead it marks up text with tags that tell the browser "this is a heading", "this is a paragraph", "this is a picture". You write HTML in a plain text editor such as Visual Studio Code or Notepad++ and save the file with the extension .html. Opening that file in a browser displays the page.

3.1.1.1 Introduction to HTML5

HTML5 is the current version of the language, published as a standard by the World Wide Web Consortium (W3C) and the WHATWG. It added meaningful structural tags, native audio and video, a drawing surface called canvas, richer form controls and storage in the browser, so that pages no longer needed plug-ins such as Flash. Because HTML5 works on phones, tablets and computers, it suits Kenya, where most people reach the web through a mobile phone.

Every HTML5 document follows the same skeleton. The first line declares the document type, the html element wraps everything, the head holds information about the page, and the body holds what the user sees.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Kisumu Teachers SACCO</title>
</head>
<body>
  <h1>Welcome to Kisumu Teachers SACCO</h1>
  <p>Save with us and grow your future.</p>
</body>
</html>

The features that distinguish HTML5 from earlier versions are:

  • Semantic elements: tags such as header, nav, section, article, aside and footer describe the purpose of a block, which helps search engines and screen readers.
  • Native multimedia: the audio and video tags play media without plug-ins.
  • Canvas and SVG: pages can draw graphics and charts directly in the browser.
  • New form controls: input types such as email, date, number and range, with built-in validation.
  • Offline and local storage: localStorage keeps small amounts of data in the browser, so a page can remember user choices.
  • Geolocation: with permission, a page can read the user's location, useful for a delivery service finding the nearest branch.

3.1.1.2 HTML Tags

A tag is a keyword inside angle brackets. Most tags come in pairs: an opening tag such as p and a closing tag such as /p, with content between them. Together, the opening tag, content and closing tag form an element. Some elements, called void elements, have no content and no closing tag, for example br, hr, img and input. Tags can be nested, but they must be closed in the reverse order in which they were opened. The sub-sections below cover the main groups of tags you need to build a complete page.

3.1.1.2.1 Structural elements and attributes

Structural elements divide a page into meaningful regions. The header element holds the logo and title, nav holds the main menu links, main holds the central content, section groups related content, article holds a self-contained item such as a news story, aside holds side content such as adverts, and footer holds contact details and copyright. The generic div and span elements have no meaning of their own and are used when no semantic element fits: div is a block container, span is an inline container.

Attributes give extra information to an element and are written inside the opening tag as name="value" pairs. Common attributes are id (a unique name for one element), class (a name shared by many elements), src (the source of an image), href (the target of a link), alt (replacement text for an image), style (inline styling) and title (a tooltip).

<header>
  <img src="logo.png" alt="Nyeri County Hospital logo" width="80">
  <h1 id="site-title">Nyeri County Hospital</h1>
</header>
<nav>
  <a href="index.html">Home</a>
  <a href="services.html">Services</a>
</nav>
<main>
  <article class="news">
    <h2>New outpatient wing opens</h2>
    <p>The wing will serve 300 patients a day.</p>
  </article>
</main>
<footer>
  <p>Contact: info@example.co.ke</p>
</footer>
3.1.1.2.2 Formatting HTML documents

Formatting tags control how text is presented. Headings run from h1 (most important) to h6 (least important); a page should have one h1 and use the others in order. The p tag makes a paragraph, br forces a line break and hr draws a horizontal rule. For emphasis, strong marks important text (usually shown bold) and em marks stressed text (usually italic). Other inline tags are b, i, u, mark (highlight), small, sub (subscript), sup (superscript), del (deleted text) and ins (inserted text). Lists use ul for bulleted lists, ol for numbered lists and li for each item, and dl, dt and dd for definition lists. The pre tag keeps spaces and line breaks exactly as typed, which suits code samples.

<h2>Farm inputs price list</h2>
<p>Prices are <strong>per 50 kg bag</strong> and may change. Water: H<sub>2</sub>O.</p>
<ol>
  <li>DAP fertiliser: Ksh 6,500</li>
  <li>CAN fertiliser: Ksh 4,800</li>
  <li>Certified maize seed: Ksh 3,200</li>
</ol>
<ul>
  <li>Delivery within Nakuru town is free</li>
  <li>Pay by M-Pesa or cash</li>
</ul>

Good practice is to separate meaning from appearance: use HTML tags for meaning and leave colours, sizes and spacing to CSS.

3.1.1.2.3 Tables

A table presents data in rows and columns. The table tag wraps the whole table, tr makes a row, th makes a header cell and td makes a data cell. The optional thead, tbody and tfoot group the header, body and footer rows. The attributes colspan and rowspan let a cell stretch across several columns or rows, and the caption tag gives the table a title. Tables should be used for data only, never to arrange the layout of a page.

<table border="1">
  <caption>Term 2 fees, Bondo Technical Institute</caption>
  <thead>
    <tr><th>Course</th><th>Tuition (Ksh)</th><th>Boarding (Ksh)</th></tr>
  </thead>
  <tbody>
    <tr><td>Electrical Installation</td><td>12,000</td><td>8,000</td></tr>
    <tr><td>Plumbing</td><td>11,500</td><td>8,000</td></tr>
    <tr><td colspan="3">Fees are payable through the school paybill.</td></tr>
  </tbody>
</table>
3.1.1.2.4 Linking Web Pages

Hyperlinks are what make the web a web. The anchor tag a with its href attribute links to another page, a file, an email address or a position on the same page. An absolute address includes the full URL (https://www.example.co.ke/about.html), while a relative address gives the path from the current file (about.html or ../images/logo.png). The target="_blank" attribute opens the link in a new tab. A link on the same page uses an id as its destination, for example href="#contacts". Links can also start an email (mailto:) or a phone call (tel:), which is very handy on a phone. Images can be wrapped in an a tag to make them clickable.

<a href="about.html">About us</a>
<a href="https://www.kra.go.ke" target="_blank">Visit KRA</a>
<a href="#contacts">Jump to contacts</a>
<a href="mailto:admissions@example.ac.ke">Email admissions</a>
<a href="tel:+254700000000">Call the front desk</a>
<h2 id="contacts">Contacts</h2>
3.1.1.2.5 Working with Layouts

Layout is the arrangement of a page's regions: header at the top, menu, content, side panel and footer. In modern HTML the regions are marked with semantic elements and positioned with CSS. Older sites built layouts from tables; this is now discouraged because tables are slow to render, hard to adapt to a phone screen and confusing to screen readers.

Two CSS systems are used for layouts. Flexbox arranges items in a single row or column, and Grid arranges items in rows and columns together. A responsive layout adapts to the screen size, using the viewport meta tag and media queries, so that a three-column layout on a laptop becomes a single column on a phone.

<div class="page">
  <header>Header</header>
  <nav>Menu</nav>
  <main>Main content</main>
  <aside>Adverts</aside>
  <footer>Footer</footer>
</div>
<style>
  .page { display: grid; grid-template-columns: 1fr 3fr 1fr; gap: 10px; }
  header, footer { grid-column: 1 / -1; }
  @media (max-width: 600px) {
    .page { grid-template-columns: 1fr; }
  }
</style>
3.1.1.2.6 Special effects and Animation using HTML5

HTML5 supports effects without third-party plug-ins. CSS transitions change a property smoothly over time, for example a button that changes colour when the mouse hovers over it. CSS animations use @keyframes to define stages of movement. The canvas element provides a drawing area that JavaScript can paint on, used for charts, games and image editing. SVG (Scalable Vector Graphics) draws shapes that stay sharp at any size, perfect for logos and icons.

<style>
  .btn { background: #0a7c3a; color: white; padding: 10px 20px; border: none;
         transition: background 0.4s, transform 0.4s; }
  .btn:hover { background: #075a2a; transform: scale(1.1); }

  @keyframes slide { from { margin-left: 0; } to { margin-left: 200px; } }
  .box { width: 50px; height: 50px; background: orange;
         animation: slide 2s infinite alternate; }
</style>
<button class="btn">Pay now</button>
<div class="box"></div>

<canvas id="c" width="200" height="100"></canvas>
<script>
  const ctx = document.getElementById("c").getContext("2d");
  ctx.fillStyle = "green";
  ctx.fillRect(10, 10, 100, 50);
</script>

Effects should be used sparingly: too much movement distracts users, slows low-end phones and uses bundles of mobile data.

3.1.1.2.7 Multimedia

Multimedia means audio, video and images. The img tag displays pictures, and its alt attribute describes the picture for users who cannot see it. The video and audio tags embed media with built-in controls, and the source tag lets you offer more than one file format so that every browser finds one it can play. The iframe tag embeds another page, such as a YouTube video or a Google Map showing a branch location.

Common formats are JPEG and PNG for photographs and graphics, WebP for smaller image files, SVG for icons, MP3 for audio and MP4 for video. In Kenya, where data is costly, compress images and avoid auto-playing large videos.

<img src="shamba.jpg" alt="Maize farm in Trans Nzoia" width="400">

<video controls width="400" poster="cover.jpg">
  <source src="training.mp4" type="video/mp4">
  <source src="training.webm" type="video/webm">
  Your browser does not support video.
</video>

<audio controls>
  <source src="radio-advert.mp3" type="audio/mpeg">
</audio>

<iframe src="https://www.youtube.com/embed/VIDEO_ID" width="400" height="225"
        title="Training video"></iframe>
3.1.1.2.8 Managing forms

Forms collect information from users: a registration form, a loan application, a login box. The form tag wraps the controls. Its action attribute gives the address of the script that will process the data and its method attribute chooses how data is sent: GET appends data to the URL and suits searches, while POST sends data in the body of the request and must be used for passwords and personal details.

Inside the form, the input tag creates most controls, and its type attribute chooses the kind: text, password, email, number, date, tel, radio, checkbox, file, submit and others. Other controls are textarea (multi-line text), select with option (drop-down lists) and button. The label tag is linked to a control by the for attribute, which improves usability. Attributes such as required, minlength, pattern, placeholder and maxlength make the browser validate input before it is sent.

<form action="register.php" method="post">
  <label for="name">Full name</label>
  <input type="text" id="name" name="name" required>

  <label for="phone">Phone</label>
  <input type="tel" id="phone" name="phone" pattern="07[0-9]{8}" placeholder="0712345678" required>

  <label for="email">Email</label>
  <input type="email" id="email" name="email">

  <label for="county">County</label>
  <select id="county" name="county">
    <option value="nairobi">Nairobi</option>
    <option value="kisii">Kisii</option>
    <option value="turkana">Turkana</option>
  </select>

  <input type="radio" id="m" name="gender" value="male"><label for="m">Male</label>
  <input type="radio" id="f" name="gender" value="female"><label for="f">Female</label>

  <input type="checkbox" id="terms" name="terms" required>
  <label for="terms">I accept the terms</label>

  <button type="submit">Register</button>
</form>

Browser validation is only a convenience; the server must always validate again, because users can bypass the browser.

3.1.1.2.9 DOM

The Document Object Model (DOM) is the browser's in-memory representation of an HTML page. When the browser loads the file, it turns every element, attribute and piece of text into an object and arranges them in a tree: html at the root, head and body as its children, and so on down. JavaScript can read and change this tree, and the page on screen updates at once. This is how a page can show a message, hide a menu or add a row to a table without reloading.

<p id="status">Waiting...</p>
<script>
  const p = document.getElementById("status");
  p.textContent = "Payment received";
  p.style.color = "green";
</script>

The main DOM methods are getElementById, getElementsByClassName, querySelector and querySelectorAll for finding elements, createElement and appendChild for adding them, and removeChild for deleting them. The CSS section below (3.1.2.8) looks at the DOM from the styling side.

3.1.1.2.10 Events

An event is something that happens on the page: a click, a key press, a form submission, a page finishing loading. HTML lets you attach event handlers to elements. The older way is an attribute such as onclick="..."; the better way is addEventListener in JavaScript, which keeps the behaviour out of the HTML and allows several handlers on one element.

Common events are click, dblclick, mouseover, mouseout, keydown, keyup, change, input, submit, focus, blur and load. The handler receives an event object that describes what happened, for example which key was pressed. Calling event.preventDefault() stops the browser's default action, such as sending a form.

<button id="btn">Check balance</button>
<script>
  document.getElementById("btn").addEventListener("click", function () {
    alert("Your balance is Ksh 12,400");
  });
</script>
3.1.1.2.11 HTML frameworks (Bootstrap and Tailwind)

A CSS framework is a ready-made collection of styles that saves you writing every rule yourself. Bootstrap provides ready components such as navigation bars, buttons, cards, modals and a 12-column responsive grid, all applied by adding class names to your HTML. Tailwind CSS takes a different approach: it supplies small utility classes, each doing one thing (p-4 adds padding, text-center centres text, bg-green-600 sets a background), which you combine directly in the HTML.

The two frameworks compare as follows:

Feature Bootstrap Tailwind CSS
Approach Pre-built components Low-level utility classes
Look of site Recognisable default style unless customised Fully custom design
Learning effort Quick to start More classes to learn
Typical use Admin panels, quick prototypes Custom branded sites

Benefits of frameworks are speed, consistency, responsiveness on all screen sizes and tested cross-browser behaviour. Drawbacks are extra file size and sameness in design. The example below uses Bootstrap from a CDN (content delivery network).

<link rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<div class="container">
  <div class="row">
    <div class="col-md-6"><div class="card p-3">Loans</div></div>
    <div class="col-md-6"><div class="card p-3">Savings</div></div>
  </div>
  <button class="btn btn-success mt-3">Apply now</button>
</div>

The same button in Tailwind would be written as class="bg-green-600 text-white px-4 py-2 rounded".

3.1.2 Cascading Style Sheets (CSS)

CSS controls the visual presentation of HTML: colours, fonts, spacing, borders, positions and layout. Keeping presentation in CSS and structure in HTML means you can change the look of an entire site, say for a new brand colour, by editing one file.

3.1.2.1 Introduction to CSS

A CSS rule has a selector, which says which elements to style, and a declaration block in curly braces holding one or more declarations. Each declaration is a property and a value separated by a colon and ended with a semicolon.

h1 {
  color: #0a7c3a;
  font-size: 32px;
}

Here h1 is the selector, color and font-size are properties, and #0a7c3a and 32px are values. Comments are written between /* and */. CSS is called "cascading" because several rules may apply to the same element, and the browser has defined ways of deciding which wins (see 3.1.2.3). Basic selectors are the type selector (p), the class selector (.notice), the ID selector (#header), the universal selector (*), grouping (h1, h2) and descendant selectors (nav a).

3.1.2.2 Various types of styles sheets

CSS can be added to a page in three ways.

An inline style is written in the style attribute of one element. It affects only that element and is hard to maintain, so it is used only for quick tests or generated content.

An internal (embedded) style sheet is written inside a style element in the head of the page. It affects that page only, and suits a single page with unique styling.

An external style sheet is a separate .css file linked from the head with the link tag. One file can style every page of a site, the browser caches it so later pages load faster, and a change in one place updates the whole site. This is the recommended method.

<!-- inline -->
<p style="color: red;">Overdue notice</p>

<!-- internal -->
<style>
  p { font-family: Arial, sans-serif; }
</style>

<!-- external -->
<link rel="stylesheet" href="css/style.css">

A fourth kind is the browser's default style sheet, which gives headings their size and links their blue colour before you add anything.

3.1.2.3 Inheritance and cascading order

Inheritance means that some properties pass from a parent element to its children. If you set the font-family and color on the body, all text inside inherits them unless a child sets its own. Text properties (color, font-family, font-size, line-height) are inherited; box properties (margin, padding, border, background) are not.

When two rules set the same property on the same element, the browser applies the cascading order:

  1. Importance: a declaration with !important beats ordinary ones. Use it rarely.
  2. Origin: author styles beat the browser's default styles.
  3. Specificity: a more specific selector wins. An inline style beats an ID selector, which beats a class selector, which beats a type selector.
  4. Source order: if specificity is equal, the rule that appears later wins.
p { color: blue; }          /* type selector: lowest */
.notice { color: green; }   /* class selector: beats p */
#alert { color: red; }      /* ID selector: beats class */

A paragraph with class="notice" and id="alert" is red. When a style does not apply as expected, the cause is nearly always specificity or source order.

3.1.2.4 Formatting text, fonts, colours and Background

CSS has properties for each aspect of text and colour.

For text: color, text-align (left, right, center, justify), text-decoration (underline, none), text-transform (uppercase, capitalize), letter-spacing, line-height and text-indent.

For fonts: font-family (give a list ending with a generic family such as sans-serif), font-size (px, em, rem or %), font-weight (normal, bold, 100 to 900) and font-style (italic). Web fonts from Google Fonts can be loaded with @import or a link tag.

For colours: a colour may be a name (green), a hexadecimal code (#0a7c3a), RGB (rgb(10,124,58)), RGBA with transparency (rgba(10,124,58,0.5)) or HSL (hsl(145,85%,26%)).

For backgrounds: background-color, background-image, background-repeat, background-position, background-size and the shorthand background.

body {
  font-family: "Segoe UI", Arial, sans-serif;
  font-size: 16px;
  line-height: 1.6;
  color: #222;
  background-color: #f5f5f5;
}
.banner {
  background-image: url("images/kenya-flag.jpg");
  background-size: cover;
  background-position: center;
  color: white;
  text-align: center;
  text-transform: uppercase;
  letter-spacing: 2px;
}

3.1.2.5 Exploring CSS class and ID attributes

Class and ID attributes connect HTML elements to CSS rules. An ID is unique: only one element on a page may have a given id, and it is selected with a hash (#). A class can be shared by many elements and one element can have several classes separated by spaces; it is selected with a dot (.).

Use IDs for one-off landmarks such as the main header, and classes for repeated styles such as buttons, cards and warnings. Many developers prefer classes for nearly all styling because they are reusable and have lower specificity, which makes rules easier to override. The same attributes are used by JavaScript to find elements.

<h1 id="main-title">Machakos Dairy Farmers</h1>
<p class="note">Milk is collected from 6 am.</p>
<p class="note important">Payments are made every 15th.</p>
<style>
  #main-title { color: darkgreen; }
  .note { border-left: 4px solid orange; padding-left: 8px; }
  .important { font-weight: bold; }
  p.note { margin: 10px 0; }   /* p elements that have class note */
</style>

3.1.2.6 HTML Tags

CSS targets HTML tags directly with type (element) selectors. Writing p { ... } styles every paragraph and a { ... } styles every link, so a consistent look can be applied across a whole site without touching the HTML. Tags can also be combined: a comma groups selectors (h1, h2, h3), a space selects descendants (nav a selects links inside nav), the greater-than sign selects direct children (ul > li), and a plus sign selects the next sibling (h2 + p).

Links have states which are styled with pseudo-classes: a:link, a:visited, a:hover and a:active, written in that order. Other useful pseudo-classes are :first-child, :nth-child(odd) for striped table rows and :focus for form fields.

a { color: #0a58ca; text-decoration: none; }
a:hover { text-decoration: underline; }
table { border-collapse: collapse; width: 100%; }
th, td { border: 1px solid #ccc; padding: 8px; }
tr:nth-child(even) { background: #f2f2f2; }
nav ul li { display: inline-block; margin-right: 12px; }

3.1.2.7 Block eleven elements

This section deals with block-level elements and how they differ from inline elements. A block-level element always starts on a new line and stretches across the full width of its container. Examples are div, p, h1 to h6, ul, ol, li, table, form, header, nav, section, article and footer. An inline element sits within a line of text and takes only the width it needs. Examples are span, a, strong, em, img and input.

Every block element is drawn as a box made of four layers, from the inside out: content, padding (space between content and border), border, and margin (space outside the border). Width and height set the content size. With box-sizing: border-box, the width includes padding and border, which makes sizes easier to predict.

.card {
  width: 300px;
  padding: 15px;
  border: 2px solid #0a7c3a;
  margin: 20px auto;     /* auto centres the block horizontally */
  box-sizing: border-box;
}

The display property changes behaviour: display: block makes an element a block, display: inline makes it inline, display: inline-block keeps it in line but allows width and height, and display: none hides it entirely. Vertical margins between two blocks collapse into the larger of the two rather than adding up.

3.1.2.8 Fundamentals of Document Object Model (DOM)

From the CSS point of view, the DOM is the tree of elements that CSS selectors are matched against. Terms from the tree are used when writing selectors: the parent of an element is the one directly above it, children are the ones directly below, siblings share a parent, and descendants are all elements below at any depth. Selectors such as nav a (descendant), ul > li (child) and h2 + p (sibling) use these relationships.

JavaScript can change styling through the DOM in two ways: by changing an element's style property, or, better, by adding or removing a class that CSS already defines.

<style>
  .hidden { display: none; }
  .highlight { background: yellow; }
</style>
<p id="msg" class="highlight">Registration is open.</p>
<button onclick="document.getElementById('msg').classList.toggle('hidden')">Show or hide</button>

The classList methods add, remove and toggle are the standard tools. Using classes keeps appearance in the CSS file and behaviour in the script, which is easier to maintain.

3.1.3 Website Scripting

Scripting adds behaviour to a web page: checking a form before it is sent, updating a total as the user types, showing a clock or loading new content without reloading the page. A script is a set of instructions run by an interpreter, in this case the browser, line by line.

3.1.3.1 Functions of scripting languages

Scripting languages are used on websites to do work that HTML and CSS cannot. The main functions are:

  • Validate input: check that a phone number has ten digits or a field is not empty before sending, saving the user a slow round trip to the server.
  • Make pages interactive: menus that open, image sliders, tabs, tooltips and pop-up dialogs respond to clicks and key presses.
  • Update content dynamically: change text, tables and lists without reloading, for example a bus company page that refreshes seat availability.
  • Communicate with the server: send and receive data in the background (Ajax), so a page can fetch results or save a form silently.
  • Process data on the server: server-side scripts talk to the database, handle logins and generate pages for each user.
  • Manage sessions and cookies: remember that a user is logged in or what is in their shopping basket.
  • Create animations and graphics: draw charts, games and visual effects.
  • Automate tasks: generate reports, send emails and resize uploaded pictures.

3.1.3.2 Types of scripting languages

Scripting languages are grouped by where the code runs.

Client-side scripts run in the user's browser. The main example is JavaScript. Their benefits are quick response and lower server load; their drawback is that the user can see and change them, so they cannot be trusted for security.

Server-side scripts run on the web server, and only their output (usually HTML) reaches the browser. Examples are PHP, Python (Django, Flask), Node.js (JavaScript on the server), Ruby, ASP.NET and Java Server Pages. They can safely access databases and hide secrets such as passwords.

Language Where it runs Typical use
JavaScript Browser (and server with Node.js) Interactivity, validation
PHP Server Dynamic pages, database access
Python Server Web apps, data processing
ASP.NET (C#) Server Enterprise web applications
Ruby Server Web applications
VBScript Browser (Internet Explorer only, now obsolete) Legacy pages

Other scripting languages related to the web are shell scripts for server administration and TypeScript, which is JavaScript with types and is compiled to JavaScript before it runs.

3.1.3.3 Java scripting

JavaScript (often written in the curriculum as "Java scripting") is the scripting language of the web. It is not related to the Java programming language apart from a similar name. It is built into every browser, so nothing needs to be installed. The sub-sections below cover its syntax and main features.

3.1.3.3.1 Introduction to JavaScript

JavaScript was created in 1995 and is now standardised as ECMAScript. It is interpreted by the browser, is case-sensitive and supports object-oriented and functional styles. With Node.js it also runs on servers.

Scripts are added to a page in two ways: inside a script element, or from an external file with the src attribute. External files are preferred and placed at the end of the body, so the page content loads first. Output can be shown with console.log() (the developer tools console), alert() (a pop-up), document.write() (avoid) or by changing the DOM.

<script src="js/app.js"></script>

<script>
  console.log("Page loaded");
  alert("Welcome to Eldoret Market online");
  document.getElementById("demo").innerHTML = "Hello, Kenya!";
</script>

Press F12 in Chrome to open the developer tools and watch the console for errors; this is the first step in debugging.

3.1.3.3.2 Statements Syntax

A JavaScript program is a list of statements. Each statement does one action and normally ends with a semicolon. Whitespace is mostly ignored. The main syntax rules are:

  • JavaScript is case-sensitive: total and Total are different names.
  • Blocks of statements are grouped in curly braces { }.
  • Single-line comments start with //, multi-line comments sit between /* and */.
  • Strings are enclosed in single quotes, double quotes or backticks.
  • Identifiers (names) begin with a letter, underscore or dollar sign, and cannot be reserved words such as if or function.
  • Names are conventionally written in camelCase, for example totalFees.
// calculate a bill
let units = 120;      // electricity units used
let rate = 25;        // Ksh per unit
let bill = units * rate;
console.log("Bill: Ksh " + bill);   /* prints Bill: Ksh 3000 */
3.1.3.3.3 Values & Variables

A variable is a named container for a value. Declare variables with let (value may change) or const (value must not be reassigned); the older var still works but has confusing scope rules and should be avoided.

JavaScript has these primitive value types:

Type Example Description
Number 42, 3.14 Whole and decimal numbers
String "Mombasa" Text
Boolean true, false Logical values
Undefined let x; Declared but not assigned
Null null Intentionally empty
BigInt 123n Very large integers

Arrays and objects are non-primitive values. The typeof operator reports the type of a value. JavaScript converts types automatically in some operations, so "5" + 2 gives "52" while "5" * 2 gives 10. To avoid surprises, convert explicitly with Number() or parseInt().

const SHOP = "Mama Njeri Stores";
let price = 150;
let quantity = 4;
let total = price * quantity;
let inStock = true;
let colours = ["red", "green", "blue"];
let customer = { name: "Achieng", county: "Kisumu" };
console.log(typeof total);        // number
console.log(SHOP + ": Ksh " + total);
3.1.3.3.4 Operators

Operators act on values (operands) to produce a result.

Group Operators Example
Arithmetic + - * / % ** ++ -- 17 % 5 gives 2
Assignment = += -= *= /= total += 50
Comparison == === != !== > < >= <= 5 === "5" is false
Logical && || ! age >= 18 && hasID
String + (concatenation) "Ksh " + 500
Ternary condition ? a : b marks >= 50 ? "Pass" : "Fail"

The strict operators === and !== compare both value and type and should be used instead of == and !=. Operator precedence follows the usual rules: multiplication and division before addition and subtraction, with brackets used to change the order.

let basic = 45000;
let allowance = 5000;
let gross = basic + allowance;           // 50000
let nssf = gross * 0.06;                 // 3000
let net = gross - nssf;                  // 47000
let status = net > 40000 ? "High" : "Standard";
3.1.3.3.5 Statements

Control statements decide which code runs and how often.

Conditional statements choose a path. The if, else if and else statements test conditions in turn; switch compares one value against many cases.

Loops repeat code. The for loop is used when the number of repetitions is known, while loops when it depends on a condition, do...while runs at least once, and for...of loops through the items of an array. The statements break (leave the loop) and continue (skip to the next round) control the flow.

let marks = 67;
if (marks >= 70) {
  console.log("Distinction");
} else if (marks >= 50) {
  console.log("Credit");
} else {
  console.log("Retake");
}

let day = "Fri";
switch (day) {
  case "Sat":
  case "Sun": console.log("Weekend"); break;
  default: console.log("Weekday");
}

for (let i = 1; i <= 5; i++) {
  console.log("Row " + i);
}

const crops = ["maize", "beans", "sorghum"];
for (const c of crops) {
  console.log(c);
}

Errors can be handled with try...catch, which prevents a failing statement from stopping the whole script.

3.1.3.3.6 Event Handling

Event handling in JavaScript means attaching a function to an event so that it runs when the event occurs. The recommended method is addEventListener, which takes the event name and a handler function. The handler receives an event object whose properties tell more about what happened, for example event.target is the element clicked and event.key is the key pressed.

A common use is validating a form before it is sent: the submit event is intercepted, the data is checked, and event.preventDefault() stops submission when something is wrong.

<form id="loanForm">
  <input type="number" id="amount" placeholder="Loan amount (Ksh)">
  <p id="error" style="color:red"></p>
  <button type="submit">Apply</button>
</form>
<script>
  document.getElementById("loanForm").addEventListener("submit", function (e) {
    const amount = Number(document.getElementById("amount").value);
    if (amount < 5000 || amount > 500000) {
      e.preventDefault();
      document.getElementById("error").textContent =
        "Enter an amount between Ksh 5,000 and Ksh 500,000";
    }
  });
</script>

Events bubble up from the clicked element to its parents, which allows event delegation: one handler on a list can serve all its items.

3.1.3.3.7 Timing Events

JavaScript can run code after a delay or at regular intervals. setTimeout(function, milliseconds) runs a function once after the delay. setInterval(function, milliseconds) runs a function repeatedly. Both return an identifier that can be passed to clearTimeout or clearInterval to cancel them. Times are in milliseconds, so 1000 is one second.

Uses include a digital clock, an image slideshow, a countdown on a one-time password (OTP) form and an automatic logout after inactivity, as in an online banking page.

<p id="clock"></p>
<p id="otp">Resend code in <span id="sec">30</span> seconds</p>
<script>
  setInterval(function () {
    document.getElementById("clock").textContent = new Date().toLocaleTimeString();
  }, 1000);

  let left = 30;
  const timer = setInterval(function () {
    left--;
    document.getElementById("sec").textContent = left;
    if (left === 0) { clearInterval(timer); }
  }, 1000);

  setTimeout(function () {
    alert("Session will expire soon");
  }, 600000);
</script>
3.1.3.3.8 Functions and objects

A function is a named block of code that can be run many times, with different inputs called parameters, and can return a result. Functions avoid repetition and make programs easier to test. They can be written as declarations, function expressions or arrow functions.

An object groups related data (properties) and actions (methods) under one name. Properties are accessed with dot notation (student.name) or square brackets. JavaScript also supplies built-in objects: Math (calculations), Date (dates and times), String, Array and JSON. The special object this refers to the object that owns the method.

function calculateVAT(amount) {
  return amount * 0.16;
}
console.log(calculateVAT(2000));   // 320

const area = (l, w) => l * w;      // arrow function
console.log(area(8, 5));           // 40

const student = {
  name: "Wanjiru",
  course: "ICT Technician",
  marks: [72, 65, 80],
  average: function () {
    const sum = this.marks.reduce((a, b) => a + b, 0);
    return sum / this.marks.length;
  }
};
console.log(student.name);                 // Wanjiru
console.log(student.average().toFixed(1)); // 72.3
console.log(Math.round(4.6));              // 5

An array of objects, such as a list of products, is the shape in which most web data is exchanged, usually as JSON text.

The rest of this chapter
🔒

Create a free account to open more of this chapter.

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒3.2 Website Backend Creation

The backend of a website is the part users never see: the server, the application code and the database that stores the data. When a member of a SACCO logs in to check a loan balance, the page in the browser is only the front; the balance itself is fetched fro…

🔒3.3 Website application frontend and backend integration

Integration is the work of connecting the frontend, which the user sees in the browser, to the backend, which holds the logic and the database. The frontend (HTML, CSS, JavaScript and jQuery) collects input and displays results. The backend (PHP with MySQL) ch…

Chapter Practical Activities

Practical 1: Explain and Demonstrate the Importance of Website Application Testing

Information Communication Technology · Level 6
Website Application
PRACTICAL ASSESSMENT
TIME: 3 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Using the provided sample website (at least 3 web pages), explain in writing and demonstrate practically the importance of website application testing before deployment.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
A working computer running Microsoft Windows 10 or above (64-bit)Sample website application files (HTML, CSS, JS, PHP as applicable)
Integrated Development Environment (IDE) or text editor (e.g. Visual Studio Code, Sublime Text)
Web browser (e.g. Google Chrome, Mozilla Firefox)
A working local web server (Xampp or Wamp)
Internet Access
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1A working computer running Microsoft Windows 10 or above (64-bit)1 Pc per Candidate
2Integrated Development Environment (IDE) or text editor (e.g. Visual Studio Code, Sublime Text)1 Pc per Candidate
3Web browser (e.g. Google Chrome, Mozilla Firefox)1 Pc per Candidate
4A working local web server (Xampp or Wamp)1 Pc per Candidate
5Internet AccessSufficient for all Candidates
6Sample website application files (HTML, CSS, JS, PHP as applicable)1 Set per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Website Application Testing Demonstration
Observed laboratory rules and used PPE (where applicable)
(Award 2 marks for full compliance with lab rules and PPE or 0)
2
Started the local web server (Xampp or Wamp) and launched sample website
(Award 2 marks for correct startup and website launch or 0)
2
Accessed all web pages of the sample website in a web browser
(Award 2 marks for accessing all pages or 0)
2
Identified and explained at least three key reasons for website application testing (e.g., functionality, security, usability, compatibility, performance)
(Award 2 marks for each well-explained reason, max 6 marks)
6
Demonstrated one functional test (e.g., form submission, navigation link) and described its importance
(Award 2 marks for practical demonstration, 2 marks for explanation or 0)
4
Demonstrated one usability or compatibility test (e.g., checking display in different browsers or devices) and described its importance
(Award 2 marks for demonstration, 2 marks for explanation or 0)
4
Sub-Total20
PRODUCT CHECKLIST
Submitted a written report (minimum 200 words) clearly summarizing the importance of testing website applications before deployment, with at least three well-explained reasons and examples from the demonstration
(Award up to 10 marks for completeness, clarity, and relevance of report; partial marks for partial fulfillment)
10
Sub-Total10
GRAND TOTAL30
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)

Practical 2: Explain and Justify Website Application Test Plans

Information Communication Technology · Level 6
Website Application
PRACTICAL ASSESSMENT
TIME: 3 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Write a report (minimum 500 words, maximum 800 words, on A4 paper) explaining and justifying the importance of structured website application test plans, including at least three real-world scenarios.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
A working computer running on 64-bit Microsoft Windows 10 or aboveA4 Ruled Paper
Integrated Development Environment (IDE) or text editor (e.g., Visual Studio Code, Sublime Text)
Web browser (e.g., Chrome, Firefox)
Internet Access
Blue/Black Pen
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1A working computer running on 64-bit Microsoft Windows 10 or above1 Pc per Candidate
2Integrated Development Environment (IDE) or text editor (e.g., Visual Studio Code, Sublime Text)1 Pc per Candidate
3Web browser (e.g., Chrome, Firefox)1 Pc per Candidate
4Internet AccessSufficient for all Candidates
5A4 Ruled Paper3 Sheets per Candidate
6Blue/Black Pen1 Pc per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Preparation and Planning
Observed candidate preparing workstation and gathering all required resources
(Award 2 marks for proper preparation, or 0)
2
Candidate clearly identifies the concept of a website application test plan
(Award 3 marks for accurate identification, or 0)
3
Sub-Total5
TASK 2: Explanation and Justification
Candidate explains in detail the importance of a structured test plan for website applications
(Award 5 marks for comprehensive explanation, or 0)
5
Candidate presents at least three distinct real-world scenarios illustrating the consequences of not using a test plan
(Award 2 marks per relevant scenario, up to 6 marks or 0)
6
Candidate justifies with specific reference to professional standards or industry practices
(Award 4 marks for detailed justification, or 0)
4
Sub-Total15
TASK 3: Report Structure and Professionalism
Candidate structures the report logically, with clear headings and coherent flow
(Award 3 marks for logical structure, or 0)
3
Candidate uses correct grammar, spelling, and professional language throughout
(Award 2 marks for professional language and accuracy, or 0)
2
Sub-Total5
PRODUCT CHECKLIST
Report is between 500 and 800 words and written on A4 paper
(Award 2 marks if word count and format are met, or 0)
2
Report addresses the importance of website application test plans with clarity and depth
(Award 5 marks for clarity and depth, or 0)
5
All three scenarios are realistic, relevant, and clearly described
(Award 2 marks per scenario, up to 6 marks or 0)
6
Justification links scenarios to professional standards and industry consequences
(Award 4 marks for strong linkage to standards, or 0)
4
Sub-Total17
GRAND TOTAL42
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)
🔒

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒Preparation of Website Application Test Plan DocumentPractical 3
🔒Classify and Describe Website Application Testing TechniquesPractical 4
🔒Functionality Testing of Website ApplicationPractical 5
🔒Black Box Testing of Sample Website ApplicationPractical 6
🔒Regression Testing of Modified Website ApplicationPractical 7
🔒Unit Testing Website Application Modules Using PHPUnitPractical 8
🔒Conduct Usability Testing and Report on User Experience for a Website ApplicationPractical 9
🔒Interface Testing for Website Application Data ExchangePractical 10
🔒Assess Website Application Compatibility Across PlatformsPractical 11
🔒Conducting Performance Testing on a Website ApplicationPractical 12
🔒Security Testing of Website Application for Common VulnerabilitiesPractical 13
🔒Selection of Website Application Testing Techniques Based on Case ScenarioPractical 14
🔒Preparation and Documentation of Website Application Test DataPractical 15