Client-Side ECMAScript/JavaScript Programming
An Introduction with Examples in HTML
|
Prof. David Bernstein
James Madison University
|
|
Computer Science Department
|
bernstdh@jmu.edu
|
Overview
- Accessing the Document from a Program:
- A Document Object Model (DOM) is a description of the
parts of document
(and their attributes) and an Application Programming Interface
(API) that defines how to
access them (e.g., the W3C DOM for HTML)
- A language binding for a DOM is a set of objects/classes
(in that language) that provides the appropriate functionality
(e.g., the ECMASCript/JavaScript bindings for
the HTML DOM)
- Including Programs in a Document:
- Typically, the document has an element that can contain
statements in a programming language (e.g., the
script
element in HTML can contain
ECMAScript/JavaScript statements or can refer to a URL
that contains such statements)
Important Aspects of the ECMAScript/JavaScript Bindings
- The Document Object:
- Represented by the
document
object
- Is a node in the "document tree"
- Elements in the Document:
- Are all nodes in the "document tree"
- Attributes of Elements:
- Are, somewhat surprisingly, also nodes in the "document tree"
but needn't be treated as such
Accessing Nodes
- The
document
Object:
- Elements:
-
getElementsByTagName()
returns a list
of descendants with the given tag name
-
getElementById()
returns the object
with the given ID (i.e., with an id
attribute
that matches the given unique ID)
- Attributes:
- Element objects have properties that correspond
to the attributes of the element that can be
accessed using the
.
operator
- You can also use the
getAttribute()
and
setAttribute()
methods
Accessing Nodes
A Simple Example
ecmascriptexamples/clientsidebasics/access.html
Event-Driven Programming
- Your Background:
- Most introductory programming courses consider
software products that "start at the top" and then
execute "step-by-step"
- Event-Driven Programmers Think About:
- The events that can occur (e.g., mouse clicks,
timing signals, key presses)
- The objects that can generate events of different kinds
(often called event generators)
- The objects/functions that need to respond to events of
different kinds (often called event receivers or event
handlers)
Important Events in Client-Side ECMAScript
- Some Document/Window Events:
-
load
is fired after the document has been
parsed and all content (e.g., images) has been
retrieved
-
unload
is fired when the user leaves
the document
- Some Mouse Events:
-
mousemove
, mouseover
,
mouseout
-
mousedown
, mouseup
,
click
, dblclick
- Some Keyboard Events:
- Some Form Events (Generated by Input Elements):
-
focus
, blur
-
change
, forminput
, input
, invalid
Event Handlers
- Defined:
- A function that is invoked when an event is generated
- Naming:
Event Handlers (cont.)
- Specification as an Attribute:
- Approach: Use the HTML element's
onevent
attribute
- Example:
<button id="calculate" onclick="calculateBMI();">Calculate</button>
- Major Drawback: Mixes code and markup (which can be
particularly problematic when different members of a team
have different responsibilities)
- Specification as a Property:
- Approach: Assign a function to the ECMAScript object's
onevent
property
- Example:
document.getElementById("calculate").onclick = calculateBMI;
- Minor Drawback: Requires the invocation of a
function (at the end of the
body
)
that assigns the handlers
An Example of Event Handling - The Functions
ecmascriptexamples/clientsidebasics/bmi.js
An Example of Event Handling - The Functions (cont.)
ecmascriptexamples/clientsidebasics/bmi-display.js
An Example of Event Handling (cont.)
Using Attributes
ecmascriptexamples/clientsidebasics/handler-attribute.html
An Example of Event Handling (cont.)
Using Properties
ecmascriptexamples/clientsidebasics/handler-property.html
An Example of Event Handling Using Properties (cont.)
ecmascriptexamples/clientsidebasics/bmi-property.js
Event Handlers - Scope and Related Issues
-
this
:
- When an event handler is invoked it is invoked as
a property of the object that generated the event
so
this
will refer to the generator
- For example, in
button.onclick = calculator.start;
,
when start()
is invoked, this
will refer to button
NOT to calculator
- You can, however, do the following:
button.onclick = function(){calculator.start();};
- The Scope Chain:
- The call/activation object is searched first
- The next object searched is not the global object it is
the object that generated the event
Event Handlers - Avoiding the Extended Scope Chain
- A Third Way to Specify Event Handlers:
- Use the
addEventListener()
method (defined
in DOM 2)
- Formal Parameters:
- The event
- The handler/listener
-
shouldCapture
(if true
the
handler captures the event;
if false
the event can bubble-up
from descendants)
- Multiple Handlers:
- If there is more than one they will all be invoked
but in no particular order
- Removing Handlers:
- Invoke
removeEventListener()
with the
same parameters
An Example (cont.)
Using Registration
ecmascriptexamples/clientsidebasics/handler-register.html
An Example Using Registration (cont.)
ecmascriptexamples/clientsidebasics/bmi-register.js
Manipulating the Presentation/Style of the Document
- The Idea:
- Have a program change the way the document is
rendered
- Approaches:
- Change the stylesheet
- Change the style attribute of individual elements
- Change the class attribute of individual elements (and have
different pre-defined styles for different classes)
- Change an individual rule in the stylesheet.
Changing the Stylesheet
- Get the Appropriate Element:
- Change the
href
Element:
- Be careful about the protocol and path
An Example of Changing the Stylesheet
An Example
ecmascriptexamples/clientsidebasics/stylesheet-change.html
An Example of Changing the Stylesheet (cont.)
ecmascriptexamples/clientsidebasics/stylesheet-change.js
Changing the Style Attribute of an Individual Element
- Steps:
- Get the element
- Get the
style
property
- Set the value of the appropriate rule
- Naming Issues:
- Names in CSS rules can contain
-
characters but ECMAScript/JavaScript identifiers can't
so identifiers omit the -
characters and
use "camel case" (e.g., font-size
becomes fontSize
)
- CSS rules can use ECMAScript/JavaScript reserved words
(e.g.,
float
) so the associated identifiers are
prefixed with css
(e.g., cssFloat
)
An Example of Changing the Style Attribute
An Example
ecmascriptexamples/clientsidebasics/styleattribute-change.html
An Example of Changing the Style Attribute (cont.)
ecmascriptexamples/clientsidebasics/styleattribute-change.js
Changing the Class of an Individual Element
- Getting Started:
- Pre-define rules for all of the classes you will need
- In the Program:
- Get the element (e.g., by ID)
- Change the class property of the element
An Example of Changing the Class
An Example
ecmascriptexamples/clientsidebasics/class-change.html
An Example of Changing the Class (cont.)
ecmascriptexamples/clientsidebasics/class-change.css
An Example of Changing the Class (cont.)
ecmascriptexamples/clientsidebasics/class-change.js
Changing a Rule
- Getting the Stylesheets:
- The
document
object has a stylesheets
collection
- Getting the Rules:
- Each member of
stylesheets
has a
cssRules
collection
- Changing a Rule:
- Example:
-
document.styleSheets[0].cssRules[i].style.color = "blue";
Changing the Document
- During Loading:
- Use
document.write()
to insert HTML text
into the document
- After Loading:
- Manipulate the nodes in the document tree
Manipulating Nodes in the Document Tree
- Get the Node of Interest:
- Directly:
node = document.getElementById("result");
- First Child:
node = parent.firstChild
- Another Child:
node = parent.childNodes[i]
- If Necessary, Construct a Node:
- For example
newTextNode = document.createTextNode("...");
- Make the Changes:
- For example
parent.replaceChild(node, newTextNode);
or parent.appendChild(newTextNode);
- For example
node.data = "...";
or
node.nodeValue = "...";
- For example, the non-standard
node.innerHTML = "...";
An Example of Manipulating Nodes
An Example that Modifies Nodes
ecmascriptexamples/clientsidebasics/bmi-calculator.html
An Example of Modifying Nodes (cont.)
ecmascriptexamples/clientsidebasics/bmi-calculator.css
An Example of Modifying Nodes (cont.)
ecmascriptexamples/clientsidebasics/bmi-calculator.js
Another Example of Manipulating Nodes
An Example that Adds Nodes to the Tree
ecmascriptexamples/clientsidebasics/addnodes.html
An Example of Adding Nodes (cont.)
ecmascriptexamples/clientsidebasics/addnodes.css
An Example of Adding Nodes in the Tree (cont.)
ecmascriptexamples/clientsidebasics/addnodes.js
Other Important Properties of the Document
Object
-
baseURI
and URL
:
- Contain the base URI (which can be modified by a
base
element and full URL of the document,respectively
- Read-only
-
domain
:
- Contains the domain name of the device that served-up
the document
- Read-only
-
lastModified
:
- Contains the date and time that the document was
last modified
- Read-only
Other Important Properties (cont.)
-
referrer
:
- Contains the URL of the document that loaded the current document
(or the empty string if the document was not opened through
a link)
- Read-only
-
cookie
:
- Contains the name/value pairs of all cookies
Some Useful Functions
- Value Checking:
- Type Checking/Conversion/Enforcement:
-
parseFloat()
and parseInt()
-
Date.parse()
- Encoding Functions:
-
escape()()
and unescape()
- Tokenizing/Parsing:
-
Location
objects have methods
for parsing URLs
Timers
- The Issue:
- One sometimes needs to have something happen after
a certain amount of time has elapsed (either once or
repeatedly)
- The Solution:
Timers (cont.)
- Execute a Statement in the Future:
-
window.setTimeout(statement,millis)
- Repeatedly Execute a Statement:
- To start:
identifier = window.setInterval(statement,millis);
- To stop:
window.clearInterval(identifier);
A Timer Example
A Simple Example of Delayed Execution
ecmascriptexamples/clientsidebasics/splashscreen.html
A Delayed Execution Example (cont.)
ecmascriptexamples/clientsidebasics/splashscreen.css
A Delayed Execution Example (cont.)
ecmascriptexamples/clientsidebasics/splashscreen.js
Another Timer Example
A Simple Example of Repeated Execution
ecmascriptexamples/clientsidebasics/fishtank.html
A Repeated Execution Example (cont.)
ecmascriptexamples/clientsidebasics/fishtank.css
A Repeated Execution Example (cont.)
ecmascriptexamples/clientsidebasics/fishtank.js
CSS Transitions instead of Timers
- The Issue:
- It sometimes makes sense to think of a document
(or a component of a document) as having a
form/presentation that changes over time
- The Solution:
- Use a CSS transition (i.e., a change in a property that
takes effect over time)
- Syntax:
- transition: property
duration [timing-function] [delay]
An Example of CSS Transitions
A Simple Example
ecmascriptexamples/clientsidebasics/ghost.html
An Example of CSS Transitions (cont.)
ecmascriptexamples/clientsidebasics/ghost.css
An Example of CSS Transitions (cont.)
ecmascriptexamples/clientsidebasics/ghost.js
There's Always More to Learn