JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
JavaScript and HTML Documents
Complete Study Notes | Chapters 5 & 6
Based on: Programming the World Wide Web — Robert W. Sebesta
Chapter 5 — JavaScript and HTML Documents
5.1 JavaScript Execution Environment
When you open a webpage in your browser, the browser creates a structured environment where JavaScript can
run. This environment is based on the Document Object Model (DOM), which is a standard that lets JavaScript
interact with every part of a webpage.
What is the DOM? The DOM (Document Object Model) is like a live map of your webpage. It converts your
HTML into a tree of objects (called nodes) that JavaScript can read and modify. When you change a DOM
object, the browser immediately updates what is shown on screen.
Key Objects in the Execution Environment
The browser creates two main objects as soon as a page loads:
• Window Object — Represents the entire browser window (or tab). Every JavaScript variable you create at
the top level automatically becomes a property of the Window object. There can be more than one
Window object (e.g., if you open pop-ups).
• Document Object — Represents the actual HTML document being displayed. It lives inside the Window
object as [Link]. It gives access to everything on the page: forms, links, images, etc.
Analogy Think of the Window as the whole shop, and the Document as the display shelf inside. JavaScript is
the shopkeeper who can rearrange items on the shelf (the Document) while standing inside the shop (the
Window).
5.2 Object Hierarchy and the DOM
5.2.1 The Object Hierarchy
The DOM organises all HTML elements into a tree (hierarchy). The topmost node is the Document node, and
every HTML element you write becomes a child node below it.
Page 1 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
Object / Node What it represents
window The browser window itself
[Link] The webpage loaded in the window
[Link][ ] Array of all <form> elements on the page
[Link][ ] Array of all <a> (anchor/link) elements
[Link][ ] Array of named anchor elements
[Link][ ] Array of all controls inside a specific form
5.2.2 DOM Levels (Versions)
The DOM evolved over time. Each level added new features:
DOM Level Key Features Added
DOM 0 (informal) Early browser model; forms/elements arrays; not an
official standard
DOM 1 Defined document structure for XHTML and XML
DOM 2 Added event model, CSS support, XML namespace
support
DOM 3 Added XPath, keyboard event handling, XML
serialisation
5.2.3 How the DOM Represents an HTML Document
Every HTML element turns into a node object in the DOM tree. Attributes of HTML tags become properties of
those node objects. For example:
<input type="text" name="address">
// In JavaScript, this becomes an object with properties:
// [Link] → 'text'
// [Link] → 'address'
Here is how a simple HTML table maps to a DOM tree:
<html>
<head><title>A simple document</title></head>
<body>
<table>
<tr>
<th>Breakfast</th>
<td>0</td><td>1</td>
</tr>
<tr>
<th>Lunch</th>
<td>1</td><td>0</td>
</tr>
</table>
</body>
</html>
Page 2 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
DOM Tree for the above HTML Document
├── <head>
│ └── <title> → 'A simple document'
└── <body>
└── <table>
├── <tr>
│ ├── <th> → 'Breakfast'
│ ├── <td> → '0'
│ └── <td> → '1'
└── <tr>
├── <th> → 'Lunch'
├── <td> → '1'
└── <td> → '0'
5.3 How to Access HTML Elements in JavaScript
Before JavaScript can read or change an HTML element, it needs the DOM address of that element — a
reference to the object that represents it. There are three main ways to do this.
Method 1 — Using the forms[ ] and elements[ ] Arrays (DOM 0)
The Document object has an array called forms[ ] and each form has an elements[ ] array. You can address any
element by its index (position number, starting at 0).
<form action="">
<input type="button" name="turnItOn">
</form>
// Access the button via index
var dom = [Link][0].elements[0];
⚠ Disadvantage If you add or remove elements later, the index numbers change and your code breaks.
Avoid using index-based access in real projects.
Method 2 — Using name Attributes
Give the form and its elements name attributes, then reference them by name in JavaScript.
<form name="myForm" action="">
<input type="button" name="rdType">
</form>
Page 3 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
// Access the button via name
var dom = [Link];
⚠ Disadvantage The XHTML 1.1 standard does not allow the name attribute on <form> elements, so this
approach can cause validation errors.
Method 3 — Using id Attributes and getElementById (Best Practice)
Give the element an id attribute (must be unique on the page), then use [Link]() to retrieve
it. This is the recommended, modern approach.
<form action="">
<input type="button" id="turnItOn">
</form>
// Access the button via id
var dom = [Link]('turnItOn');
✔ Best Practice Always use id attributes and getElementById(). The id value must be unique — no two
elements on the same page can share an id.
Method 4 — Implicit Arrays for Checkboxes & Radio Buttons
When multiple checkboxes or radio buttons share the same name, the browser creates an implicit array
automatically. You can loop through it to find which ones are checked.
<form id="vehicleGroup">
<input type="checkbox" name="vehicle" value="car" /> Car
<input type="checkbox" name="vehicle" value="truck" /> Truck
<input type="checkbox" name="vehicle" value="bike" /> Bike
</form>
// Count how many checkboxes are checked
var numChecked = 0;
var dom = [Link]('vehicleGroup');
for (var i = 0; i < [Link]; i++) {
if ([Link][i].checked) {
numChecked++;
}
}
// [Link] is the implicit array of all checkboxes named 'vehicle'
Access Method When to Use
forms[ ].elements[ ] (index) Avoid — breaks when page structure changes
[Link] (name) Legacy; causes XHTML validation errors on <form>
getElementById('id') (id) ✔ Always prefer this — clear, safe, modern
Implicit arrays (for groups) Use for radio buttons and checkbox groups
Page 4 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
5.4 Events and Event Handling
5.4.1 What is an Event?
An event is something that happens in the browser — a user clicks a button, moves the mouse, presses a key, or
the page finishes loading. In JavaScript, events are objects. Their names are case-sensitive (e.g., click is valid,
Click is not).
5.4.2 What is an Event Handler?
An event handler (also called an event listener) is a JavaScript function you write to run when a particular event
occurs. This style of programming is called event-driven programming.
The most common use of event handlers is to validate user input on the client side — this saves a round-trip to
the server.
Important Rule Never use [Link]() inside an event handler. Events fire after the page is fully
loaded, so calling write() would overwrite the entire document content with new content.
5.4.3 Connecting Events to Handlers — Registration
Connecting an event handler to an event is called registration. There are two ways to do it in DOM 0:
Way 1 — Inline in the HTML tag (using event attributes):
<!-- Simple: put the code directly in the attribute -->
<input type='button' onclick="alert('You clicked the button!')">
<!-- Better: call a function defined elsewhere -->
<input type='button' onclick='myHandler();'>
Way 2 — Assign to the element property in JavaScript (separates HTML from JS):
// This must run AFTER the HTML element exists on the page
[Link]('myButton').onclick = myHandler;
// Notice: no parentheses () after myHandler
// We are assigning the FUNCTION ITSELF, not calling it
Inline vs. Property Assignment Inline (onclick='...'): Easier to pass parameters to the handler function.
Property assignment (.onclick = fn): Keeps HTML and JavaScript separate; also lets you change the handler
later at runtime.
5.4.4 Common Events and Their HTML Attributes
Page 5 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
Event Name HTML Attribute When it Fires
click onclick User clicks an element
dblclick ondblclick User double-clicks an element
mouseover onmouseover Mouse pointer moves over an element
mouseout onmouseout Mouse pointer leaves an element
mousedown onmousedown Mouse button is pressed down
mouseup onmouseup Mouse button is released
mousemove onmousemove Mouse pointer moves
focus onfocus Element receives input focus (clicked or tabbed
into)
blur onblur Element loses input focus
change onchange Input value changes and element loses focus
select onselect User selects text in an input or textarea
submit onsubmit User submits a form
load onload The page (body) has finished loading
unload onunload The user leaves the page
keydown onkeydown A keyboard key is pressed
keyup onkeyup A keyboard key is released
keypress onkeypress A key is pressed and released
5.4.5 Focus and Blur Explained
An element gets focus (becomes active for input) in three ways: (1) the user clicks on it, (2) the user tabs to it, or
(3) JavaScript calls its focus() method. Losing focus is called blurring — triggered by clicking elsewhere or calling
blur().
5.5 Handling Events from the <body> Element
The two most common events on the <body> element are load and unload.
• onload — Fired after the entire page finishes loading. Use this to run setup code (e.g., populate a
dropdown, set initial values).
• onunload — Fired just before the user leaves the page. Use this for cleanup (e.g., close pop-up windows
that the page opened).
<body onload="setupPage();" onunload="cleanUp();">
...
</body>
5.6 Handling Events from Buttons, Checkboxes, and Radio Buttons
Page 6 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
5.6.1 Button Click Events
<!-- Method 1: Inline attribute -->
<input type="button" id="freeButton" onclick="freeButtonHandler();">
<!-- Method 2: Assign via JavaScript (preferred) -->
<script>
function freeButtonHandler() {
alert('Button clicked!');
}
// Assign AFTER the element is defined in HTML
[Link]('freeButton').onclick = freeButtonHandler;
</script>
5.6.2 Radio Button Click Events
Radio buttons are mutually exclusive — only one in a group can be selected at a time. You can pass parameters
when using inline registration:
<input type="radio" name="color" value="red" onclick="colorChosen('red')"> Red
<input type="radio" name="color" value="blue" onclick="colorChosen('blue')" > Blue
<input type="radio" name="color" value="green" onclick="colorChosen('green')"> Green
function colorChosen(selectedColor) {
alert('You chose: ' + selectedColor);
}
5.7 Handling Events from Text Boxes — Validating Input
5.7.1 Text Box Events
Text boxes (and password fields) can fire four events:
• focus — User clicks into the box
• blur — User clicks away from the box
• change — Content changed and the box lost focus
• select — User highlights text inside the box
5.7.2 Why Validate on the Client Side?
Checking form data with JavaScript in the browser is faster than sending the data to the server and waiting for
an error response. If something is wrong, the user gets instant feedback.
Standard approach to handling a validation error:
1. Show an alert message explaining the problem
2. Use focus() to put the cursor back in the problematic field
3. Use select() to highlight the text for easy correction
4. Return false from the handler to prevent the form from submitting
5.7.3 Validation Example — Password Check
Page 7 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
function validatePassword() {
var pw1 = [Link]('pw1').value;
var pw2 = [Link]('pw2').value;
if (pw1 !== pw2) {
alert('Passwords do not match. Please re-enter.');
[Link]('pw2').focus(); // move cursor back
[Link]('pw2').select(); // highlight text
return false; // prevents form submission
}
return true; // allow submission
}
// Attach to the submit button
[Link]("submitBtn").onclick = validatePassword;
5.7.4 Validation Using Regular Expressions
Regular expressions are powerful patterns for matching text. JavaScript's .test() method checks whether a string
matches a pattern.
// Pattern: Name in format: FirstName, LastName, M (each capitalised)
var namePattern = /^[A-Z][a-z]+, ?[A-Z][a-z]+, ?[A-Z]\.?$/;
// Pattern: Phone in format: 555-867-5309
var phonePattern = /^\d{3}-\d{3}-\d{4}$/;
// Usage
if () {
alert('Name must be: FirstName, LastName, M');
[Link]();
return false;
}
Regex Quick Reference ^ → Start of string
$ → End of string
[A-Z] → Any uppercase letter
[a-z]+ → One or more lowercase letters
\d{3} → Exactly 3 digits
? → Previous item is optional (0 or 1 times)
\. → A literal dot (backslash escapes the dot)
5.8 The DOM 2 Event Model
5.8.1 Overview
DOM 2 introduced a more advanced and flexible event system. Unlike DOM 0 where only one handler per event
per element was possible, DOM 2 allows multiple handlers on the same element for the same event.
In DOM 2, an event object is automatically created when an event fires and passed to the handler. This object
contains useful information such as which element was clicked or where the mouse is.
Page 8 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
5.8.2 Event Propagation (The Three Phases)
When an event fires on an element, it doesn't just affect that element — it travels through the DOM tree in
three phases:
5. Capturing Phase — The event travels DOWN the tree from the document root to the target element.
Handlers enabled for capture are executed along the way.
6. Target Phase — The event reaches the actual element that triggered it. All handlers on that element are
executed.
7. Bubbling Phase — The event travels BACK UP the tree from the target to the root. Handlers at each
ancestor node are executed.
Visual: Event Propagation document
↓ (1. Capturing — going down)
body
↓
div
↓
[button] ← (2. Target — event fires here)
↑
div (3. Bubbling — going back up)
↑
body
↑
document
Events that do NOT bubble: load, unload, blur, focus.
Events that DO bubble: all mouse events (click, mousedown, mouseup, mousemove, etc.).
You can stop the event from continuing to propagate by calling [Link]() inside any handler. To
prevent the browser's default action (like following a link), call [Link]().
Why Bubbling is Useful Instead of adding an event handler to every button in a calculator, you can place
ONE handler on their parent container. When any button is clicked, the event bubbles up to the parent, and
the parent's handler deals with it. This is called event delegation.
Page 9 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
5.8.3 Registering Handlers with addEventListener
In DOM 2, handlers are called listeners and are registered using addEventListener() which takes three
parameters:
// [Link](eventName, handlerFunction, useCapture)
var btn = [Link]('myBtn');
[Link]('click', myHandler, false);
// ↑ ↑ ↑
// event name function false = bubbling phase
// true = capturing phase
function myHandler(event) {
// 'event' is the event object, passed automatically
[Link]('Clicked element:', [Link]);
[Link]('Handler running on:', [Link]);
}
// To remove a handler:
[Link]('click', myHandler, false);
Event Object Property What it Tells You
[Link] The element that originally triggered the event
[Link] The element where the handler is currently running
[Link] / [Link] Mouse X/Y position relative to the browser window
[Link] / [Link] Mouse X/Y position relative to the screen
[Link]() Method — stops the event from bubbling/capturing
further
[Link]() Method — prevents the browser's default action
5.9 The navigator Object
The navigator object allows JavaScript to detect information about the browser it is running in. This was more
important in older times when browsers differed significantly; today it is mostly used for feature detection.
// Detect browser name and version
var browserName = [Link];
var browserVersion = [Link];
alert('Browser: ' + browserName + '\nVersion: ' + browserVersion);
// Note: Modern browsers often report 'Netscape' as appName
// even if they are Chrome or Firefox, for compatibility reasons.
5.10 DOM Tree Traversal and Modification
5.10.1 Navigating the Tree
Every element node in the DOM has properties that let you move to related nodes — parents, children, and
siblings.
Page 10 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
Property What it References
[Link] The parent element of this node
[Link] The first child node inside this element
[Link] The last child node inside this element
[Link] The sibling node that comes just before this one
[Link] The sibling node that comes just after this one
[Link] A list (NodeList) of all child nodes
5.10.2 Modifying the Tree
You can add, remove, or replace elements in the DOM tree dynamically:
Method What it Does
[Link](newNode) Adds newNode as the last child of parent
[Link](newNode, refNode) Inserts newNode before refNode inside parent
[Link](newNode, oldNode) Replaces oldNode with newNode
[Link](childNode) Removes childNode from parent
[Link]('tag') Creates a new element node (e.g., 'p', 'div')
[Link]('text') Creates a new text node with the given text
// Example: create and add a new paragraph to the page
var newPara = [Link]('p');
var text = [Link]('Hello, this is new!');
[Link](text);
[Link](newPara);
// Example: remove an element
var el = [Link]('oldDiv');
[Link](el);
Chapter 6 — Dynamic Documents with JavaScript
A dynamic document is a webpage that changes its appearance or content after it has loaded — without
reloading the page. JavaScript achieves this by manipulating DOM properties and CSS styles at runtime.
6.2 Element Positioning with CSS
6.2.1 The position Property
Page 11 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
CSS gives you control over exactly where elements appear on screen using the position property, combined with
left, top, right, and bottom offsets.
position Value Meaning
static (default) Normal flow — elements stack left-to-right, top-to-
bottom. left and top are ignored.
relative Moved relative to where it WOULD have been in
normal flow. Other elements are unaffected.
absolute Positioned relative to its nearest positioned ancestor
(or the page if none). Removed from normal flow.
Direction of offsets:
• Positive top → element moves DOWN
• Negative top → element moves UP
• Positive left → element moves RIGHT
• Negative left → element moves LEFT
<!-- Absolute positioning example -->
<p style="position:absolute; left:100px; top:200px;">
This text appears 100px from the left and 200px from the top.
</p>
<!-- Relative positioning — creates a superscript effect -->
Normal text <span style="position:relative; top:-8px; font-
size:smaller;">superscript</span>
Note on z-index When two absolutely positioned elements overlap, the one with the higher z-index appears
on top. z-index is an integer (no units). Example: style='z-index: 10;'
6.3 Moving Elements Dynamically
Because CSS positions are just properties, JavaScript can change them at any time to move elements around the
screen. The position mode must be relative or absolute — static ignores top/left values.
function moveImage(x, y) {
var img = [Link]('myImage');
[Link] = x + "px"; // Must append "px" units
[Link] = y + "px";
}
// HTML
<img id="myImage" src="[Link]"
style="position:absolute; left:0px; top:0px;" >
<!-- Buttons to move the image -->
<input type="number" id="xCoord" placeholder="X">
<input type="number" id="yCoord" placeholder="Y">
<button onclick="moveImage(
Page 12 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
[Link]('xCoord').value,
[Link]('yCoord').value
);">Move</button>
6.4 Controlling Element Visibility
The CSS visibility property controls whether an element is visible. Importantly, a hidden element still takes up
space in the layout (unlike display:none which completely removes it from the flow).
function showElement() {
[Link]('myDiv').[Link] = 'visible';
}
function hideElement() {
[Link]('myDiv').[Link] = 'hidden';
}
function toggleElement() {
var el = [Link]('myDiv');
if ([Link] === 'hidden') {
[Link] = 'visible';
} else {
[Link] = 'hidden';
}
}
CSS Property Effect when 'hidden'
visibility: hidden Element is invisible BUT still occupies its space in the
layout
display: none Element is completely removed from the layout —
no space reserved
6.5 Changing Colors and Fonts Dynamically
6.5.1 Changing Colors
Every element has a style property that mirrors its CSS. You can change colors in response to events.
// Change background colour when user types in a text box
[Link]("colorBox").onchange = function() {
var color = [Link]; // e.g. "red" or "#FF0000"
[Link] = color;
};
// Note: CSS property names with dashes become camelCase in JS:
// background-color → backgroundColor
// font-size → fontSize
// z-index → zIndex
6.5.2 Changing Fonts
// Make a link grow bold on hover, and shrink back on mouseout
var link = [Link]("myLink");
Page 13 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
[Link] = function() {
[Link] = "bold";
[Link] = "1.2em";
[Link] = "#C05A00";
};
[Link] = function() {
[Link] = "normal";
[Link] = "1em";
[Link] = ""; // Reset to default
};
CSS ↔ JavaScript Property Name Conversion CSS uses hyphenated names; JavaScript uses camelCase
versions:
background-color → backgroundColor
font-size → fontSize
font-weight → fontWeight
border-radius → borderRadius
z-index → zIndex
6.6 Dynamic Content
JavaScript can change the actual content of the page — not just its style. Common approaches:
• [Link] — Changes the text inside input fields and textareas
• [Link] — Changes the HTML content inside any element (powerful but use with care)
• [Link] — Changes only the plain text inside an element (safer than innerHTML)
// Show a help message in a textarea when hovering over an input
var helpBox = [Link]('helpArea');
var inputs = [Link]('input');
var helpMessages = ['Enter your full name', 'Enter your email', 'Enter your age'];
for (var i = 0; i < [Link]; i++) {
(function(index) {
inputs[index].onmouseover = function() {
[Link] = helpMessages[index];
};
inputs[index].onmouseout = function() {
[Link] = '';
};
})(i);
}
6.7 Stacking Elements with z-index
Page 14 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
The z-index CSS property controls which element appears on top when elements overlap. Higher z-index = closer
to the viewer. JavaScript can change z-index at runtime to bring elements forward or push them back.
// Bring an element to the front
function bringToFront(id) {
[Link](id).[Link] = "100";
}
// Send it to the back
function sendToBack(id) {
[Link](id).[Link] = "1";
}
// Note: z-index is stored as a string in style properties
6.8 Locating the Mouse Cursor
Mouse event objects carry coordinates telling you exactly where the cursor was when the event fired.
Property Coordinates Relative To
[Link], [Link] Top-left corner of the browser viewport (visible area)
[Link], [Link] Top-left corner of the entire physical screen
[Link], [Link] Top-left corner of the full page (including scrolled
area)
// Display mouse coordinates as the mouse moves
[Link] = function(event) {
var x = [Link];
var y = [Link];
[Link]("coords").textContent =
"X: " + x + " Y: " + y;
};
6.9 Reacting to a Mouse Click
You can combine mouse position tracking with visibility to create interactive effects — for example, making an
element appear at the location of a click.
var tooltip = [Link]('tooltip');
[Link] = function(event) {
// Move tooltip to where the user clicked
[Link] = [Link] + "px";
[Link] = [Link] + "px";
[Link] = "visible";
};
[Link] = function() {
[Link] = "hidden";
};
Page 15 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
6.10 Slow Movement of Elements — Using Timers
6.10.1 setTimeout — Execute Once, Later
setTimeout(code, delay) schedules a piece of JavaScript code to run one time after a specified delay in
milliseconds (1 second = 1000 ms).
// Run a function once, after 2 seconds
setTimeout(function() {
alert('2 seconds have passed!');
}, 2000);
// Or pass a function name:
setTimeout(myFunction, 2000);
6.10.2 setInterval — Execute Repeatedly
setInterval(function, delay) repeatedly calls a function at the specified interval.
var counter = 0;
var intervalId = setInterval(function() {
counter++;
[Link]("display").textContent = counter;
if (counter >= 10) {
clearInterval(intervalId); // Stop after 10 iterations
}
}, 1000); // Every 1 second
6.10.3 Animated Movement with setTimeout
To animate an element smoothly, use setTimeout recursively — move a little, wait, move a little more:
function moveText(currentLeft, targetLeft) {
var el = [Link]('movingText');
if (currentLeft < targetLeft) {
currentLeft += 5; // Move 5px to the right
[Link] = currentLeft + "px";
// Schedule next step after 20ms
setTimeout(function() {
moveText(currentLeft, targetLeft);
}, 20);
}
// Stops when currentLeft reaches targetLeft
}
// Start animation: move from 0px to 400px
moveText(0, 400);
Function Behaviour
setTimeout(fn, ms) Runs fn once after ms milliseconds
setInterval(fn, ms) Runs fn every ms milliseconds, indefinitely
clearTimeout(id) Cancels a scheduled setTimeout
clearInterval(id) Cancels a running setInterval
Page 16 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
6.11 Dragging and Dropping Elements
Drag-and-drop is implemented by dynamically changing event handlers based on user actions.
The logic works in three stages:
8. onmousedown on the element — 'Grab' it: record current position, assign onmousemove and
onmouseup handlers to the document.
9. onmousemove on the document — Update the element's left and top to follow the mouse.
[Link] on the document — 'Drop' it: remove the onmousemove and onmouseup handlers.
var el = [Link]('draggable');
var offsetX, offsetY;
[Link] = function(event) {
offsetX = [Link] - [Link];
offsetY = [Link] - [Link];
[Link] = drag;
[Link] = drop;
};
function drag(event) {
[Link] = ([Link] - offsetX) + "px";
[Link] = ([Link] - offsetY) + "px";
}
function drop() {
[Link] = null; // Remove handlers when done
[Link] = null;
}
// HTML
<div id="draggable"
style="position:absolute; width:100px; height:100px;
background:lightblue; cursor:grab;">
Drag me!
</div>
Quick Reference Summary
Most Important Methods to Remember
Method / Property Chapter Purpose
[Link]('id') 5.3 Get a reference to an HTML element by its id
[Link] = fn 5.4 Register a click event handler
[Link]('ev', fn, 5.8 DOM 2 way to register any event handler
false)
[Link] 5.8 Which element triggered the event
[Link]() 5.8 Stop browser's default action
Page 17 of 18
JavaScript & HTML Documents — Study Notes | Chapters 5 & 6
Method / Property Chapter Purpose
[Link]() 5.8 Stop event from bubbling/capturing
[Link] = '50px' 6.3 Move element horizontally
[Link] = '50px' 6.3 Move element vertically
[Link] 6.4 'visible' or 'hidden'
[Link] 6.5 Change background colour
[Link] 6.7 Control stacking order
[Link] / [Link] 6.8 Mouse position in browser window
setTimeout(fn, ms) 6.10 Run code once after a delay
setInterval(fn, ms) 6.10 Run code repeatedly at an interval
clearInterval(id) 6.10 Stop a setInterval
[Link](node) 5.10 Add a child node to an element
[Link](node) 5.10 Remove a child node from an element
Exam Tips & Common Mistakes
Top Things to Remember for Internals 1. getElementById is the preferred way to access elements —
always use it.
2. Event names are case-sensitive: 'click' ✔, 'Click' ✗
3. When assigning a handler: [Link] = myFn (NO parentheses after myFn)
4. Never use [Link]() inside an event handler.
5. DOM 2 uses addEventListener(); DOM 0 uses onclick= attribute or property.
6. Bubbling: events travel UP the tree after the target; capturing travels DOWN.
7. CSS position must be 'absolute' or 'relative' before top/left move anything.
8. CSS property names in JS use camelCase: background-color → backgroundColor
9. [Link] and [Link] require units: '50px', not just 50.
10. setTimeout runs once; setInterval runs repeatedly — clear it with clearInterval.
Page 18 of 18