How unit 3 is examined
This unit covers CSS (need, syntax, box model, positioning, CSS3) and client-side JavaScript with the DOM, forms and DHTML events. Marks sit in Need for CSS, JavaScript programs, DOM forms and validation, and DHTML events and data binding.
Need for CSS
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Medium weight</span>
Definition. <mark>CSS (Cascading Style Sheets) is a style sheet language that describes the presentation (colour, font, layout) of an HTML document, keeping it separate from the content.</mark>
Key points.
- CSS separates content (HTML) from presentation, so one file can restyle a whole website.
- Inline CSS uses the
styleattribute on a single element and has the highest priority. - Internal CSS is written in a
<style>block inside<head>and applies to one page. - External CSS is stored in a
.cssfile linked with<link rel="stylesheet" href="a.css">and applies to many pages. - Cascading means that when rules conflict, inline beats internal, which beats external, and a more specific selector beats a general one.
- Advantages: consistent look, easy maintenance (change one file), reuse, smaller pages and faster loading because the file is cached, and more layout control than HTML.
- Disadvantages: different browsers may render the same CSS differently, a large or complex style sheet is hard to manage, an external file needs an extra request, and CSS has no logic or programming ability.
Example.
<link rel="stylesheet" href="style.css"> <!-- external -->
<style> p { color: blue; } </style> <!-- internal -->
<p style="color:red">Hello</p> <!-- inline -->
Answer frame. Open with the definition; write the three types with one line of code each; list advantages then disadvantages in two short groups of four; close by saying external CSS is recommended for real sites.
Asked: [7 marks] (Nov 2022) Explain about CSS and its advantages in brief. Write down the advantages and disadvantages of using style sheets.
Basic syntax and structure, using CSS
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. A CSS rule is selector { property: value; }, where the selector picks the HTML elements and each declaration sets one property.
Key points.
- The selector types are element (
p), class (.note), id (#top), universal (*) and grouped (h1, h2). - Each declaration ends with a semicolon and all declarations sit inside curly braces.
- Comments are written as
/* comment */. - A class can be used on many elements, but an id must be unique in a page.
p.note { color: green; font-size: 14px; }
Background images, colors and properties
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. Background properties set the colour or image behind an element's content.
Key points.
background-coloraccepts a name, hex (#ff0000),rgb()orhsl()value.background-image: url("pic.jpg")places an image, andbackground-repeat(repeat,no-repeat,repeat-x) controls tiling.background-positionplaces the image (center top) andbackground-attachment: fixedkeeps it still while scrolling.colorsets the text colour, andbackground: red url(a.png) no-repeat;is the shorthand.
Manipulating texts, using fonts
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. Text properties control the look of text blocks, and font properties control the typeface.
Key points.
font-familygives a list of fonts with a generic fallback, such asArial, sans-serif.font-size,font-weight(bold) andfont-style(italic) set size, thickness and slant.text-align(left, right, center, justify),text-decoration(underline, none),text-transform(uppercase) andtext-indentshape the text.line-heightandletter-spacingset the vertical and horizontal spacing.
Borders and boxes, margins, padding lists
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. The box model treats every element as a box made of content, padding, border and margin, from inside out.
Key points.
- Padding is the space between content and border, and it takes the element's background.
- The border is the line around the padding, set with
border: 2px solid black;. - Margin is the transparent space outside the border that separates neighbouring elements.
- Total width is content plus padding plus border plus margin, unless
box-sizing: border-boxis used. - Lists are styled with
list-style-type(disc, circle, square, decimal),list-style-imageandlist-style-position.
Positioning using CSS
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Not asked since 2022</span>
Definition. The position property decides how an element is placed in the page.
Key points.
staticis the default and follows the normal flow.relativeoffsets the element from its normal place usingtop/left, while its old space is kept.absoluteremoves the element from the flow and places it relative to the nearest positioned ancestor.fixedplaces it relative to the browser window so it stays during scrolling, andstickyswitches between relative and fixed.z-indexdecides which overlapping element is on top.
CSS2 and overview of CSS3
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Low weight</span>
Definition. CSS2 (1998) is the older single specification; CSS3 is a set of independent modules that adds modern visual features.
| Point | CSS2 | CSS3 |
|---|---|---|
| Structure | One large specification | Split into modules (selectors, colour, backgrounds) |
| Selectors | Basic (element, class, id, descendant) | Attribute and structural selectors such as :nth-child |
| Borders | Square only | Rounded corners (border-radius), box-shadow |
| Effects | No animation | transition, animation, transform |
| Layout | Floats and positioning | Flexbox, Grid, multi-column, media queries for responsive design |
| Colour and fonts | Named, hex, rgb; system fonts | rgba, hsl, gradients, @font-face web fonts |
Limitations of pure CSS.
- CSS has no variables-and-logic (no loops or conditions), so it cannot compute or decide.
- It cannot respond to user actions such as clicks or validate a form, so interactivity needs JavaScript.
- Browsers support new CSS3 features unevenly, which needs prefixes and fallbacks.
- It cannot change HTML content or fetch data.
Answer frame. Write the 6-row table for the comparison; then list four limitations; close by saying CSS is combined with JavaScript for dynamic pages.
Asked: [7 marks] (Nov 2023) Distinguish between CSS2 and CSS3. Write the limitations of using entirely "pure" CSS.
JavaScript: client-side scripting, variables, functions, conditions, loops, pop-up boxes
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Medium weight</span>
Definition. <mark>JavaScript is a lightweight, interpreted, client-side scripting language that runs in the browser to make web pages dynamic.</mark>
Key points.
- Scripts are placed inside a script element, in head or body, or in an external
.jsfile. - Variables are declared with
var,letorconst, and the language is dynamically typed. - Functions are defined with
function name(params) { ... return x; }and called by name. - Conditions use
if / else if / elseandswitch; loops usefor,whileanddo-while. - Pop-up boxes:
alert()shows a message,confirm()returns true or false, andprompt()returns the typed text as a string. document.write()writes into the page, andparseInt()orNumber()converts a prompt string to a number.
Example (date and time).
// HTML page: html > body > a script element containing:
var d = new Date();
document.write("Date: " + d.toLocaleDateString() + "<br>Time: " + d.toLocaleTimeString());
// Output: Date: 29/9/2026 Time: 10:15:30 AM
getDate(), getMonth(), getHours() and toLocaleString() are the other Date methods.
Example (arithmetic in alert).
// HTML page: html > body > a script element containing:
var a = parseFloat(prompt("Enter first number"));
var b = parseFloat(prompt("Enter second number"));
alert("Sum = " + (a + b) + "\nDifference = " + (a - b) +
"\nProduct = " + (a * b) + "\nQuotient = " + (a / b));
// Inputs 8 and 2 show: Sum = 10, Difference = 6, Product = 16, Quotient = 4
Answer frame. Open with the definition of JavaScript; write the full HTML wrapper with the script tag; use a Date object or prompt inputs as asked; close with the output line.
Asked: [7 marks] (Nov 2022) Write a JavaScript which displays current date and time. Asked: [7 marks] (Nov 2023) Write a simple JavaScript that performs arithmetic operations and displays the result in an alert() dialog. Pitfall:
prompt()returns a string, soa + bjoins text ("2"+"3"="23") unless it is converted first.
Advance JavaScript: objects, own objects, DOM and browser environment
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Low weight</span>
Definition. A JavaScript object is a collection of properties and methods; built-in objects include Math, Date, String and Array, and own objects are created with {} or a constructor.
Key points.
- Math is a built-in object with no constructor, so its methods are called directly, as in
Math.sqrt(16). - Five Math methods:
Math.abs(-7.5)gives 7.5;Math.ceil(4.2)gives 5;Math.floor(4.8)gives 4;Math.max(3,9,5)gives 9;Math.pow(2,3)gives 8. - Others are
Math.min(),Math.sqrt()andMath.random()(a number from 0 up to but not including 1). - An own object:
var car = {name:"Swift", speed:80, show:function(){ return this.name; }};. - The browser environment exposes
window(top object),document,location,historyandnavigator, and the DOM is the tree of the page underdocument.
Asked: [7 marks] (Nov 2022) Write any five methods of Math object of JavaScript.
Manipulation using DOM, forms and validations
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Medium weight</span>
Definition. <mark>The DOM (Document Object Model) represents an HTML page as a tree of objects that JavaScript can read and change, and form validation checks user input before it is sent.</mark>
Key points.
- Elements are found with
getElementById(),getElementsByName(),getElementsByTagName()orquerySelector(). - Content and style are changed through
innerHTML,valueandstyle.color. - Radio buttons (
type="radio") share onename, so only one can be selected; check boxes (type="checkbox") allow several. - Both have the properties
name,valueandchecked(true or false), and events such asonclick. - Form validation runs in the
onsubmithandler and returnsfalseto stop submission. - E-mail validation uses a regular expression such as
/^[^\s@]+@[^\s@]+\.[a-z]{2,}$/.
Example (e-mail validation).
// HTML: form id="f" containing input type="text" id="em" and a submit button
function check() {
var re = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i;
if (!re.test(document.getElementById("em").value)) {
alert("Invalid e-mail"); return false; }
return true;
}
document.getElementById("f").onsubmit = check; // false blocks the submit
Example (radio and check box).
// HTML: input type="radio" name="g" value="M" id="r1"; input type="checkbox" id="c1"
if (document.getElementById("r1").checked) alert("Male selected");
var boxes = document.getElementsByName("hobby"); // check boxes sharing a name
for (var i = 0; i < boxes.length; i++) if (boxes[i].checked) alert(boxes[i].value);
Answer frame. For the short note, define both objects, list name, value and checked, then show the code; for e-mail validation, draw the form, write the regex function, and close by saying the form submits only when it returns true.
Asked: [7 marks] (Nov 2022) Write short note on radio buttons and check boxes object in JavaScript. Asked: [7 marks] (Nov 2023) Write a JavaScript code for E-mail validation using HTML form.
DHTML: combining HTML, CSS and JavaScript, events and buttons
<span style="display:inline-block;padding:.16em .6em;border:1.5px solid currentColor;border-radius:999px;font-size:.68em;font-weight:700;letter-spacing:.06em;text-transform:uppercase;opacity:.75">Medium weight</span>
Definition. <mark>DHTML (Dynamic HTML) is the combination of HTML for structure, CSS for style, JavaScript for behaviour and the DOM to make pages that change without reloading.</mark>
Key points.
- An event is an action such as
onclick,onmouseover,onkeypress,onloadoroncontextmenu, and a handler is the function that runs. - Handlers are attached as an HTML attribute or with
element.addEventListener("click", fn). - Event flow has a capturing phase (window down to the target) and then a bubbling phase (target back up to the window).
event.stopPropagation()stops bubbling andevent.preventDefault()cancels the default action.- A context menu is made by hiding a
<div>menu, catchingoncontextmenu, callingpreventDefault(), and placing the div at the mouse positionclientX/clientY. - Data binding links page elements to a data source object so that the table is filled without scripting:
datasrcnames the source anddatafldnames the field. - Data binding advantages: less code, the page updates from the data, and sorting or filtering is done without a server request.
<figure class="ds-fig" style="margin:1.4rem 0;overflow-x:auto"><svg xmlns="http://www.w3.org/2000/svg" id="dsfig-u3-01" viewBox="0 0 467 80" width="467" height="80" role="img" aria-label="W window, D document, B body, T target element"><style>#dsfig-u3-01 .e{stroke:#454C5A;stroke-width:1.4;fill:none}#dsfig-u3-01 .e.hi{stroke:#2340B8;stroke-width:2.6}#dsfig-u3-01 .n{fill:#FFFFFF;stroke:#16181D;stroke-width:1.4}#dsfig-u3-01 .n.hi{fill:#E3E9FC;stroke:#2340B8;stroke-width:2.2}#dsfig-u3-01 .n.rb-b{fill:#16181D;stroke:#16181D}#dsfig-u3-01 .n.rb-r{fill:#BD3227;stroke:#BD3227}#dsfig-u3-01 text{font-family:"JetBrains Mono",ui-monospace,Menlo,Consolas,monospace;font-size:13px}#dsfig-u3-01 .t{fill:#16181D;font-weight:500}#dsfig-u3-01 .t.inv{fill:#FFFFFF;font-weight:700}#dsfig-u3-01 .kd{stroke:#16181D;stroke-width:1.2}#dsfig-u3-01 .dot{fill:#16181D}#dsfig-u3-01 .ann{fill:#2340B8;font-size:11px;font-weight:700}#dsfig-u3-01 .lbl{fill:#6F7787;font-family:system-ui,-apple-system,sans-serif;font-size:12px;font-weight:700}#dsfig-u3-01 .ptr{fill:#2340B8;font-size:12px;font-weight:700}#dsfig-u3-01 .ah{fill:#454C5A}#dsfig-u3-01 .ah.hi{fill:#2340B8}#dsfig-u3-01 .wl rect{fill:#FFFFFF;stroke:#DCE0E7}#dsfig-u3-01 .wl .t{font-size:12px;font-weight:700}#dsfig-u3-01 .wl.hi rect{fill:#2340B8;stroke:#2340B8}#dsfig-u3-01 .wl.hi .t{fill:#FFFFFF}html.dark #dsfig-u3-01 .e{stroke:#B1B7C3}html.dark #dsfig-u3-01 .e.hi{stroke:#8FA3FF}html.dark #dsfig-u3-01 .n{fill:#161920;stroke:#E6E8ED}html.dark #dsfig-u3-01 .n.hi{fill:#1E2748;stroke:#8FA3FF}html.dark #dsfig-u3-01 .n.rb-b{fill:#E6E8ED;stroke:#E6E8ED}html.dark #dsfig-u3-01 .n.rb-r{fill:#FF7E71;stroke:#FF7E71}html.dark #dsfig-u3-01 .t{fill:#E6E8ED}html.dark #dsfig-u3-01 .t.inv{fill:#0F1115}html.dark #dsfig-u3-01 .kd{stroke:#E6E8ED}html.dark #dsfig-u3-01 .dot{fill:#E6E8ED}html.dark #dsfig-u3-01 .ann{fill:#8FA3FF}html.dark #dsfig-u3-01 .lbl{fill:#858D9C}html.dark #dsfig-u3-01 .ptr{fill:#8FA3FF}html.dark #dsfig-u3-01 .ah{fill:#B1B7C3}html.dark #dsfig-u3-01 .ah.hi{fill:#8FA3FF}html.dark #dsfig-u3-01 .wl rect{fill:#161920;stroke:#2A2E37}html.dark #dsfig-u3-01 .wl.hi rect{fill:#8FA3FF;stroke:#8FA3FF}html.dark #dsfig-u3-01 .wl.hi .t{fill:#0F1115}</style><defs><marker id="ah3" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah" d="M0,1 L9,5 L0,9 z"/></marker><marker id="ahh3" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path class="ah hi" d="M0,1 L9,5 L0,9 z"/></marker></defs><path class="e" d="M59,40 L148,40" marker-end="url(#ah3)"/><path class="e" d="M188,40 L277,40" marker-end="url(#ah3)"/><path class="e" d="M315,48.4 Q362.5,72 408.2,49.3" marker-end="url(#ah3)"/><path class="e" d="M410,31.6 Q362.5,8 316.8,30.7" marker-end="url(#ah3)"/><g class="wl"><rect x="331.3" y="51.4" width="61.5" height="18" rx="9"/><text class="t" x="362.1" y="60.4" dy=".35em" text-anchor="middle">capture</text></g><g class="wl"><rect x="335.8" y="10.6" width="54.3" height="18" rx="9"/><text class="t" x="362.9" y="19.6" dy=".35em" text-anchor="middle">bubble</text></g><circle class="n" cx="40" cy="40" r="18"/><text class="t" x="40" y="40" dy=".35em" text-anchor="middle">W</text><circle class="n" cx="169" cy="40" r="18"/><text class="t" x="169" y="40" dy=".35em" text-anchor="middle">D</text><circle class="n" cx="298" cy="40" r="18"/><text class="t" x="298" y="40" dy=".35em" text-anchor="middle">B</text><circle class="n" cx="427" cy="40" r="18"/><text class="t" x="427" y="40" dy=".35em" text-anchor="middle">T</text></svg><figcaption style="font-size:.82em;opacity:.72;margin-top:.45rem">W window, D document, B body, T target element</figcaption></figure>
Example (context menu).
// HTML: div id="m" with display:none, position:absolute and text "Copy | Paste"
document.oncontextmenu = function(e) {
e.preventDefault();
var m = document.getElementById("m");
m.style.left = e.clientX + "px"; m.style.top = e.clientY + "px";
m.style.display = "block";
};
document.onclick = function() { document.getElementById("m").style.display = "none"; };
Example (data binding).
<object id="d" classid="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83">
<param name="DataURL" value="stud.csv"></object>
<table datasrc="#d"><tr><td><span datafld="name"></span></td></tr></table>
Data binding of this kind was Internet Explorer specific.
Answer frame. For event handling, define event, handler and the two phases, then show the context-menu code with steps; for data binding, define DHTML, give the source object and the datasrc/datafld example, and close with the advantages.
Asked: [7 marks] (Nov 2022) Explain in detail DOM event handling. Also explain with an example of creating a context menu. Asked: [7 marks] (Nov 2023) Describe data binding in DHTML.
Last-minute revision
- CSS = Cascading Style Sheets; three types are inline, internal and external, and inline has the highest priority.
- Rule syntax is
selector { property: value; }. - Box model from inside out: content, padding, border, margin.
- Position values: static, relative, absolute, fixed, sticky.
- CSS3 adds rounded corners, animations, transitions, flexbox and media queries.
prompt()returns a string,confirm()returns true or false,alert()shows a message.- Five Math methods: abs, ceil, floor, max, pow (also min, sqrt, random).
- Date object:
new Date()withtoLocaleString(),getDate()andgetTime(). - Radio and check box properties: name, value, checked.
- Validation goes in
onsubmitand returns false to block submission. - DHTML = HTML + CSS + JavaScript + DOM.
- Data binding uses
datasrcanddatafld.
Memory hooks
- CSS priority: I-I-E (Inline, Internal, External) from strongest to weakest.
- Box model: "CPBM", Content, Padding, Border, Margin, from the centre out.
- Pop-ups: alert tells, confirm asks yes or no, prompt asks for text.
- Event flow: capture goes down, bubble comes up.
- DHTML = "HCJD": HTML, CSS, JavaScript, DOM.
Coverage checklist
- Need for CSS: Q9 (CSS and advantages and disadvantages).
- basic syntax and structure, using CSS: covered, not asked.
- background images, colors and properties: covered, not asked.
- manipulating texts, using fonts: covered, not asked.
- borders and boxes, margins, padding lists: covered, not asked.
- positioning using CSS: covered, not asked.
- CSS2, Overview and features of CSS3: Q2 (CSS2 vs CSS3, limitations of pure CSS).
- JavaScript : Client side scripting with JavaScript, variables, functions, conditions, loops and repetition, Pop up boxes: Q5 (date and time), Q6 (arithmetic in alert).
- Advance JavaScript: JavaScript and objects, JavaScript own objects, the DOM and web browser environments: Q1 (Math methods).
- Manipulation using DOM, forms and validations: Q7 (radio and check boxes), Q8 (e-mail validation).
- DHTML : Combining HTML, CSS and JavaScript, Events and buttons: Q3 (event handling and context menu), Q4 (data binding).