- Forward


Client-Side ECMAScript/JavaScript Programming
An Introduction with Examples in HTML


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Overview
Back SMYC Forward
  • 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
Back SMYC Forward
  • 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
Back SMYC Forward
  • The document Object:
    • Has global scope
  • 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
Back SMYC Forward

A Simple Example Click here for a demonstration.

ecmascriptexamples/clientsidebasics/access.html
 
Event-Driven Programming
Back SMYC Forward
  • 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
Back SMYC Forward
  • 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:
    • keydown, keyup, keypress
  • Some Form Events (Generated by Input Elements):
    • focus, blur
    • change, forminput, input, invalid
Event Handlers
Back SMYC Forward
  • Defined:
    • A function that is invoked when an event is generated
  • Naming:
    • onevent
Event Handlers (cont.)
Back SMYC Forward
  • 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
Back SMYC Forward
ecmascriptexamples/clientsidebasics/bmi.js
 
An Example of Event Handling - The Functions (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/bmi-display.js
 
An Example of Event Handling (cont.)
Back SMYC Forward

Using Attributes Click here for a demonstration.

ecmascriptexamples/clientsidebasics/handler-attribute.html
 
An Example of Event Handling (cont.)
Back SMYC Forward

Using Properties Click here for a demonstration.

ecmascriptexamples/clientsidebasics/handler-property.html
 
An Example of Event Handling Using Properties (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/bmi-property.js
 
Event Handlers - Scope and Related Issues
Back SMYC Forward
  • 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
Back SMYC Forward
  • 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.)
Back SMYC Forward

Using Registration Click here for a demonstration.

ecmascriptexamples/clientsidebasics/handler-register.html
 
An Example Using Registration (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/bmi-register.js
 
Manipulating the Presentation/Style of the Document
Back SMYC Forward
  • 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
Back SMYC Forward
  • Get the Appropriate Element:
    • By ID
    • By tag name
  • Change the href Element:
    • Be careful about the protocol and path
An Example of Changing the Stylesheet
Back SMYC Forward

An Example Click here for a demonstration.

ecmascriptexamples/clientsidebasics/stylesheet-change.html
 
An Example of Changing the Stylesheet (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/stylesheet-change.js
 
Changing the Style Attribute of an Individual Element
Back SMYC Forward
  • 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
Back SMYC Forward

An Example Click here for a demonstration.

ecmascriptexamples/clientsidebasics/styleattribute-change.html
 
An Example of Changing the Style Attribute (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/styleattribute-change.js
 
Changing the Class of an Individual Element
Back SMYC Forward
  • 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
Back SMYC Forward

An Example Click here for a demonstration.

ecmascriptexamples/clientsidebasics/class-change.html
 
An Example of Changing the Class (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/class-change.css
 
An Example of Changing the Class (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/class-change.js
 
Changing a Rule
Back SMYC Forward
  • Getting the Stylesheets:
    • The document object has a stylesheets collection
  • Getting the Rules:
    • Each member of stylesheets has a cssRules collection
  • Changing a Rule:
    • Use the style property
  • Example:
    • document.styleSheets[0].cssRules[i].style.color = "blue";
Changing the Document
Back SMYC Forward
  • 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
Back SMYC Forward
  1. Get the Node of Interest:
    • Directly: node = document.getElementById("result");
    • First Child: node = parent.firstChild
    • Another Child: node = parent.childNodes[i]
  2. If Necessary, Construct a Node:
    • For example newTextNode = document.createTextNode("...");
  3. 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
Back SMYC Forward

An Example that Modifies Nodes Click here for a demonstration.

ecmascriptexamples/clientsidebasics/bmi-calculator.html
 
An Example of Modifying Nodes (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/bmi-calculator.css
 
An Example of Modifying Nodes (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/bmi-calculator.js
 
Another Example of Manipulating Nodes
Back SMYC Forward

An Example that Adds Nodes to the Tree Click here for a demonstration.

ecmascriptexamples/clientsidebasics/addnodes.html
 
An Example of Adding Nodes (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/addnodes.css
 
An Example of Adding Nodes in the Tree (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/addnodes.js
 
Other Important Properties of the Document Object
Back SMYC Forward
  • 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.)
Back SMYC Forward
  • 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
Back SMYC Forward
  • Value Checking:
    • isFinite() and isNaN()
  • Type Checking/Conversion/Enforcement:
    • parseFloat() and parseInt()
    • Date.parse()
  • Encoding Functions:
    • escape()() and unescape()
  • Tokenizing/Parsing:
    • Location objects have methods for parsing URLs
Timers
Back SMYC Forward
  • The Issue:
    • One sometimes needs to have something happen after a certain amount of time has elapsed (either once or repeatedly)
  • The Solution:
    • Use a timer
Timers (cont.)
Back SMYC Forward
  • 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
Back SMYC Forward

A Simple Example of Delayed Execution Click here for a demonstration.

ecmascriptexamples/clientsidebasics/splashscreen.html
 
A Delayed Execution Example (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/splashscreen.css
 
A Delayed Execution Example (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/splashscreen.js
 
Another Timer Example
Back SMYC Forward

A Simple Example of Repeated Execution Click here for a demonstration.

ecmascriptexamples/clientsidebasics/fishtank.html
 
A Repeated Execution Example (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/fishtank.css
 
A Repeated Execution Example (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/fishtank.js
 
CSS Transitions instead of Timers
Back SMYC Forward
  • 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
Back SMYC Forward

A Simple Example Click here for a demonstration.

ecmascriptexamples/clientsidebasics/ghost.html
 
An Example of CSS Transitions (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/ghost.css
 
An Example of CSS Transitions (cont.)
Back SMYC Forward
ecmascriptexamples/clientsidebasics/ghost.js
 
There's Always More to Learn
Back -