0% found this document useful (0 votes)
58 views114 pages

Java Script Basics

This document provides an overview of JavaScript. It discusses that JavaScript is an object-oriented, dynamically typed scripting language that runs in web browsers. It allows for client-side scripting which can improve performance by offloading processing to the client. Asynchronous JavaScript and XML (AJAX) improved JavaScript by enabling asynchronous data requests in the background without page reloads. Frameworks like jQuery now make AJAX programming easier.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
58 views114 pages

Java Script Basics

This document provides an overview of JavaScript. It discusses that JavaScript is an object-oriented, dynamically typed scripting language that runs in web browsers. It allows for client-side scripting which can improve performance by offloading processing to the client. Asynchronous JavaScript and XML (AJAX) improved JavaScript by enabling asynchronous data requests in the background without page reloads. Frameworks like jQuery now make AJAX programming easier.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 114

JavaScript: Client-Side

Scripting

Chapter 6

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Textbook to be published by Pearson ©
Ed2015
in early
Pearson
2014
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
http://www.funwebdev.com
Objectives
1 What is
JavaScript 2 JavaScript Design

3 Using
JavaScript 4 Syntax

5 JavaScript
Objects 6 The DOM

7 JavaScript
Events 8 Forms

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 1 of 8

WHAT IS JAVASCRIPT
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
What is JavaScript

it is an object-oriented, dynamically typed, scripting language.

JavaScript is object oriented in that almost everything in the language is


an object. For instance, variables are objects in that they have
constructors, properties, and methods.

Unlike more familiar object-oriented languages such as Java, C#, and


Visual Basic, functions in JavaScript are also objects. the objects in
JavaScript are prototype- based rather than class-based, which means
that while JavaScript shares some syntactic features of Java or C#, it is
also quite different from those languages.

Given that JavaScript approaches objects far differently than other


languages, and does not have a formal class mechanism nor inheritance
syntax, we might say that it is a strange object-oriented language.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


JavaScript is dynamically typed (also called weakly typed) in that
variables can be easily (or implicitly) converted from one data type to
another.

In a programming language such as Java, variables are statically typed,


in that the data type of a variable is defined by the programmer (e.g.,
int abc) and enforced by the compiler.

With JavaScript, the type of data a variable can hold is assigned at


runtime and can change during run time as well.

it is a client-side scripting language, and runs right inside the browser

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


What isn’t JavaScript
It’s not Java

Although it contains the word Java, JavaScript and Java are


vastly different programming languages with different uses.
Java is a full-fledged compiled, object-oriented language,
popular for its ability to run on any platform with a JVM
installed.
Conversely, JavaScript is one of the world’s most popular
languages, with fewer of the object-oriented features of
Java, and runs directly inside the browser, without the need
for the JVM.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Client-Side Scripting
Let the client compute

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Client-Side Scripting

There are many advantages of client-side scripting:


• Processing can be offloaded from the server to client
machines, thereby reducing the load on the server.
• The browser can respond more rapidly to user events
than a request to a remote server ever could, which
improves the user experience.
• JavaScript can interact with the downloaded HTML in a
way that the server cannot, creating a user experience
more like desktop software than simple HTML ever
could.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Client-Side Scripting
There are challenges

The disadvantages of client-side scripting are mostly


related to how programmers use JavaScript in their
applications.
• There is no guarantee that the client has JavaScript
enabled
• The unusual characteristics between various browsers
and operating systems make it difficult to test for all
potential client configurations. What works in one
browser, may generate an error in another.
• JavaScript-heavy web applications can be complicated
to debug and maintain.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


JavaScript is not the only type of client-side scripting.
Adobe Flash is a vector based drawing and animation program, a
video file format, and a software platform that has its own
JavaScript-like programming language called ActionScript.
Flash is often used for animated advertisements and online games,
and can also be used to construct web interfaces.
Flash objects (not videos) are in a format called SWF (Shockwave
Flash) and are included within an HTML document via the <object>
tag. The SWF file is then downloaded by the browser and then the
browser delegates control to a plug-in to execute the Flash file.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Randy Connolly and Ricardo Hoar Fundamentals of Web Development
A browser plug-in is a software add-on that extends the
functionality and capabilities of the browser by allowing it to view
and process different types of web content.
It should be noted that a browser plug-in is different than a
browser extension these also extend the functionality of a
browser but are not used to process downloaded content. For
instance, FireBug in the Firefox browser provides a wide range of
tools that help the developer understand what’s in a page; it
doesn’t really alter how the browser displays a page.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Client-Side Applets
Java Applets

The second (and oldest) of these alternatives to JavaScript is


Java applets.
An applet is a term that refers to a small application that
performs a relatively small task. Java applets are written
using the Java programming language and are separate
objects that are included within an HTML document via the
<applet> tag, downloaded, and then passed on to a Java
plug-in.
This plug-in then passes on the execution of the applet
outside the browser to the Java Runtime Environment (JRE)
that is installed on the client’s machine.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Both Flash plug-ins and Java applets are losing support by major
players for a number of reasons.
First, Java applets require the JVM be installed and up to date, which
some players are not allowing for security reasons (Apple’s iOS
powering iPhones and iPads supports neither Flash nor Java
applets).
Second, Flash and Java applets also require frequent updates, which
can annoy the user and present security risks. With the universal
adoption of JavaScript and HTML5, JavaScript remains the most
dynamic and important client-side scripting language for the modern
web developer.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


JavaScript History

• JavaScript was introduced by Netscape in their


Navigator browser back in 1996.
• JavaScript is in fact an implementation of a
standardized scripting language called ECMAScript
• JavaScript was only slightly useful, and quite often,
very annoying to many users

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


JavaScript in Modern Times
AJAX

JavaScript became a much more important part of web


development in the mid 2000s with AJAX.
AJAX is both an acronym as well as a general term.
• As an acronym it means Asynchronous JavaScript And
XML.
• The most important feature of AJAX sites is the
asynchronous data requests.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


HTTP request-response loop
Without JavaScript

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


HTTP request-response loop
Detail

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Asynchronous data requests
The better AJAX way

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


AJAX provides web authors with a way to avoid the visual and temporal
deficiencies of normal HTTP interactions. With AJAX web pages, it is
possible to update sections of a page by making special requests of the
server in the background, creating the illusion of continuity

This type of AJAX development can be difficult but thankfully, the other
key development in the history of JavaScript has made AJAX
programming significantly less tricky. This development has been the
creation of JavaScript frameworks, such as jQuery, Prototype, ASP.NET
AJAX, and MooTools. These JavaScript frameworks reduce the amount
of JavaScript code required to perform typical AJAX tasks. Some of these
extend the JavaScript language; others provide functions and objects to
simplify the creation of complex user interfaces.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 2 of 8
JAVASCRIPT DESIGN PRINCIPLES

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Layers
They help organize

When designing software to solve a problem, it is often


helpful to abstract the solution a little bit to help build a
cognitive model in your mind that you can then implement.
Perhaps the most common way of articulating such a
cognitive model is via the term layer.
In object-oriented programming, a software layer is a way
of conceptually grouping programming classes that have
similar functionality and dependencies.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Layers
Common Layers

• Presentation layer. Classes focused on the user


interface.
• Business layer. Classes that model real-world entities,
such as customers, products, and sales.
• Data layer. Classes that handle the interaction with the
data sources.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Layers
Just a conceptual idea

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Graceful Degradation and
Progressive Enhancement
Over the years, browser support for different JavaScript
objects has varied. Something that works in the current
version of Chrome might not work in IE version 8; something
that works in a desktop browser might not work in a mobile
browser.
There are two strategies:
• graceful degradation
• progressive enhancement

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Graceful Degradation

With this strategy you develop your site for the abilities of
current browsers.
For those users who are not using current browsers, you
might provide an alternate site or pages for those using
older browsers that lack the JavaScript (or CSS or HTML5)
used on the main site.
The idea here is that the site is “degraded” (i.e., loses
capability) “gracefully” (i.e., without pop-up JavaScript error
codes or without condescending messages telling users to
upgrade their browsers)

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Graceful Degradation

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Progressive Enhancement

In this case, the developer creates the site using CSS,


JavaScript, and HTML features that are supported by all
browsers of a certain age or newer.
To that baseline site, the developers can now
“progressively” (i.e., for each browser) “enhance” (i.e., add
functionality) to their site based on the capabilities of the
users’ browsers.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Progressive Enhancement

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 3 of 8

WHERE DOES JAVASCRIPT GO?


Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Where does JavaScript go?

JavaScript can be linked to an HTML page in a number of


ways.
• Inline
• Embedded
• External

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Inline JavaScript
Mash it in

Inline JavaScript refers to the practice of including JavaScript


code directly within certain HTML attributes
Inline JavaScript is a real maintenance nightmare

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Embedded JavaScript
Better

Embedded JavaScript refers to the practice of placing


JavaScript code within a <script> element

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


External JavaScript
Better

JavaScript supports this separation by allowing links to an


external file that contains the JavaScript.
By convention, JavaScript external files have the extension .js.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 4 of 8

SYNTAX
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
JavaScript Syntax

We will briefly cover the fundamental syntax for the most


common programming constructs including
• variables,
• assignment,
• conditionals,
• loops, and
• arrays
before moving on to advanced topics such as events and
classes.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


JavaScript’s Reputation
Precedes it?

• Everything is type sensitive, including function, class, and variable


names.
• The scope of variables in blocks is not supported. This means
variables declared inside a loop may be accessible outside of the
loop, counter to what one would expect.
• There is a === operator, which tests not only for equality but type
equivalence.
• Null and undefined are two distinctly different states for a variable.
• Semicolons are not required, but are permitted (and encouraged).
• There is no integer type, only number, which means floating-point
rounding errors are prevalent even with values intended to be
integers.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Variables
var

Variables in JavaScript are dynamically typed, meaning a


variable can be an integer, and then later a string, then
later an object, if so desired.
This simplifies variable declarations, so that we do not
require the familiar type fields like int, char, and String.
Instead we use var
Assignment can happen at declaration-time by appending
the value to the declaration, or at run time with a simple
right-to-left assignment

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Variables
Assignment

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


There are two styles of comment in JavaScript,
the end-of-line comment, which starts with two slashes //,
and the block comment, which begins with /* and ends with
*/

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Comparison Operators
True or not True

Operator Description Matches (x=9)


== Equals (x==9) is true
(x=="9") is true

=== Exactly equals, including type (x==="9") is false

(x===9) is true

<,> Less than, Greater Than (x<5) is false


<= , >= Less than or equal, greater than or equal (x<=9) is true
!= Not equal (4!=x) is true
!== Not equal in either value or type (x!=="9") is true

(x!==9) is false

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Logical Operators

The Boolean operators and, or, and not and their truth tables
are listed in Table 6.2. Syntactically they are represented with
&& (and), || (or), and ! (not).

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Conditionals
If, else if, …, else

JavaScript’s syntax is almost identical to that of PHP, Java,


or C when it comes to conditional structures such as if and
if else statements. In this syntax the condition to test is
contained within ( ) brackets with the body contained in { }
blocks.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Loops
Round and round we go

Like conditionals, loops use the ( ) and { } blocks to define


the condition and the body of the loop.
You will encounter the while and for loops
While loops normally initialize a loop control variable
before the loop, use it in the condition, and modify it within
the loop.
var i=0; // initialise the Loop Control Variable
while(i < 10){ //test the loop control variable
i++; //increment the loop control variable
}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


For Loops
Counted loops

A for loop combines the common components of a loop:


initialization, condition, and post-loop operation into one
statement.
This statement begins with the for keyword and has the
components placed between ( ) brackets, semicolon (;)
separated as shown

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Functions
Functions are the building block for modular code in
JavaScript, and are even used to build pseudo-classes, which
you will learn about later.
They are defined by using the reserved word function and
then the function name and (optional) parameters.
Since JavaScript is dynamically typed, functions do not
require a return type, nor do the parameters require type.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Functions
Example

Therefore a function to raise x to the yth power might be defined as:


function power(x,y){
var pow=1;
for (var i=0;i<y;i++){
pow = pow*x;
}
return pow;
}
And called as
power(2,10);

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Alert
Not really used anymore, console instead

The alert() function makes the browser show a pop-up to


the user, with whatever is passed being the message
displayed. The following JavaScript code displays a simple
hello world message in a pop-up:
alert ( "Good Morning" );
Using alerts can get tedious fast. When using debugger
tools in your browser you can write output to a log with:
console.log("Put Messages Here");
And then use the debugger to access those logs.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Errors using try and catch

When the browser’s JavaScript engine encounters an error,


it will throw an exception. These exceptions interrupt the
regular, sequential execution of the program and can stop
the JavaScript engine altogether. However, you can
optionally catch these errors preventing disruption of the
program using the try–catch block

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Throw your own
Exceptions that is.

Although try-catch can be used exclusively to catch built-in


JavaScript errors, it can also be used by your programs, to
throw your own messages. The throw keyword stops
normal sequential execution, just like the built-in
exceptions

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Tips
With Exceptions

Try-catch and throw statements should be used for


abnormal or exceptional cases in your program.
Throwing an exception disrupts the sequential execution
of a program. When the exception is thrown all
subsequent code is not executed until the catch statement
is reached.
This reinforces why try-catch is for exceptional cases.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 5 of 8

JAVASCRIPT OBJECTS
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
JavaScript Objects
Objects not Classes

JavaScript is not a full-fledged object-oriented


programming language.
It does not have classes per se, and it does not support
many of the patterns you’d expect from an object-
oriented language like inheritance and polymorphism.
The language does, however, support objects.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


JavaScript Objects
Not full-fledged O.O.

Objects can have constructors, properties, and methods


associated with them.
There are objects that are included in the JavaScript
language; you can also define your own kind of objects.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Constructors

Normally to create a new object we use the new keyword,


the class name, and ( ) brackets with n optional parameters
inside, comma delimited as follows:
var someObject = new ObjectName(p1,p2,..., pn);
For some classes, shortcut constructors are defined
var greeting = "Good Morning";
vs the formal:
var greeting = new String("Good Morning");

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Properties
Use the dot

Each object might have properties that can be accessed,


depending on its definition.
When a property exists, it can be accessed using dot
notation where a dot between the instance name and the
property references that property.
//show someObject.property to the user
alert(someObject.property);

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Methods
Use the dot, with brackets

Objects can also have methods, which are functions


associated with an instance of an object. These methods are
called using the same dot notation as for properties, but
instead of accessing a variable, we are calling a method.
someObject.doSomething();
Methods may produce different output depending on the
object they are associated with because they can utilize the
internal properties of the object.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Objects Included in JavaScript

A number of useful objects are included with JavaScript


including:
• Array
• Boolean
• Date
• Math
• String
• Dom objects

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Arrays

Arrays are one of the most used data structures. In practice,


this class is defined to behave more like a linked list in that it
can be resized dynamically, but the implementation is
browser specific, meaning the efficiency of insert and delete
operations is unknown.
The following code creates a new, empty array named
greetings:
var greetings = new Array();

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Arrays
Initialize with values

To initialize the array with values, the variable declaration would


look like the following:
var greetings = new Array("Good Morning", "Good Afternoon");
or, using the square bracket notation:
var greetings = ["Good Morning", "Good Afternoon"];

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Arrays
Access and Traverse

To access an element in the array you use the familiar square


bracket notation from Java and C-style languages, with the index
you wish to access inside the brackets.
alert ( greetings[0] );
One of the most common actions on an array is to traverse
through the items sequentially. Using the Array object’s length
property to determine the maximum valid index. We have:
for (var i = 0; i < greetings.length; i++){
alert(greetings[i]);
}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Arrays
Index and Value

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Arrays
Modifying an array

To add an item to an existing array, you can use the push


method.
greetings.push("Good Evening");
The pop method can be used to remove an item from the
back of an array.
Additional methods: concat(), slice(), join(), reverse(), shift(),
and sort()

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Math

The Math class allows one to access common mathematic


functions and common values quickly in one place.
This static class contains methods such as max(), min(),
pow(), sqrt(), and exp(), and trigonometric functions such as
sin(), cos(), and arctan().
Many mathematical constants are defined such as PI, E,
SQRT2, and some others
Math.PI; // 3.141592657
Math.sqrt(4); // square root of 4 is 2.
Math.random(); // random number between 0 and 1

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


String

The String class has already been used without us even knowing
it.
Constructor usage
var greet = new String("Good"); // long form constructor
var greet = "Good"; // shortcut constructor
Length of a string
alert (greet.length); // will display "4"

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


String
Concatenation and so much more

var str = greet.concat("Morning"); // Long form concatenation


var str = greet + "Morning"; // + operator concatenation
Many other useful methods exist within the String class, such as
• accessing a single character using charAt()
• searching for one using indexOf().
Strings allow splitting a string into an array, searching and
matching with split(), search(), and match() methods.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Date
Not that kind

The Date class is yet another helpful included object you


should be aware of. It allows you to quickly calculate the
current date or create date objects for particular dates. To
display today’s date as a string, we would simply create a
new object and use the toString() method.
var d = new Date();
// This outputs Today is Mon Nov 12 2012 15:40:19 GMT-
0700
alert ("Today is "+ d.toString());

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Window

The window object in JavaScript corresponds to the browser


itself. Through it, you can access the current page’s URL, the
browser’s history, and what’s being displayed in the status bar,
as well as opening new browser windows.
In fact, the alert() function mentioned earlier is actually a
method of the window object.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 6 of 8
THE DOCUMENT OBJECT MODEL (DOM)

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


The DOM
Document Object Model

JavaScript is almost always used to interact with the HTML


document in which it is contained.
This is accomplished through a programming interface (API)
called the Document Object Model.
According to the W3C, the DOM is a:
Platform- and language-neutral interface that will allow
programs and scripts to dynamically access and update the
content, structure and style of documents.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


The DOM
Seems familiar, because it is!

We already know all about the DOM, but by another name.


The tree structure from Chapter 2 (HTML) is formally called
the DOM Tree with the root, or topmost object called the
Document Root.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


DOM Nodes

In the DOM, each element within the HTML document is


called a node. If the DOM is a tree, then each node is an
individual branch.
There are:
• element nodes,
• text nodes, and
• attribute nodes
All nodes in the DOM share a common set of properties and
methods.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


DOM Nodes
Element, text and attribute nodes

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


DOM Nodes
Essential Node Object properties

Property Description
attributes Collection of node attributes

childNodes A NodeList of child nodes for this node


firstChild First child node of this node.
lastChild Last child of this node.
nextSibling Next sibling node for this node.
nodeName Name of the node
nodeType Type of the node
nodeValue Value of the node
parentNode Parent node for this node.
previousSibling Previous sibling node for this node.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Document Object
One root to ground them all

The DOM document object is the root JavaScript object


representing the entire HTML document.
It contains some properties and methods that we will use
extensively in our development and is globally accessible as
document.
// specify the doctype, for example html
var a = document.doctype.name;
// specify the page encoding, for example ISO-8859-1
var b = document.inputEncoding;

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Document Object
Document Object Methods

Method Description
createAttribute() Creates an attribute node

createElement() Creates an element node


createTextNode() Create a text node
getElementById(id) Returns the element node whose id attribute
matches the passed id parameter.

getElementsByTagName(name) Returns a nodeList of elements whose tag name


matches the passed name parameter.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Accessing nodes
getElementById(), getElementsByTagName()

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Element node Object

The type of object returned by the method


document.getElementById() described in the previous
section is an element node object.
This represents an HTML element in the hierarchy,
contained between the opening <> and closing </> tags for
this element.
• can itself contain more elements

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Element node Object
Essential Element Node Properties

Property Description
className The current value for the class attribute of
this HTML element.
id The current value for the id of this
element.
innerHTML Represents all the things inside of the tags.
This can be read or written to and is the
primary way which we update particular
div's using JS.
style The style attribute of an element. We can
read and modify this property.
tagName The tag name for the element.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Randy Connolly and Ricardo Hoar Fundamentals of Web Development
Modifying a DOM element

The document.write() method is used to create output to


the HTML page from JavaScript. The modern JavaScript
programmer will want to write to the HTML page, but in a
particular location, not always at the bottom
Using the DOM document and HTML DOM element objects,
we can do exactly that using the innerHTML property

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Now the HTML of our document has been modified to reflect that change.

<div id="latestComment">

<p>By Ricardo on <time>September 15, 2012</time></p>

<p>Easy on the HDR buddy.</p>

<p>Updated this div with JS</p>

</div>

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Modifying a DOM element
More verbosely, and validated

Although the innerHTML technique works well (and is very


fast), there is a more verbose technique available to us that
builds output using the DOM.
DOM functions createTextNode(), removeChild(), and
appendChild() allow us to modify an element in a more
rigorous way

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Changing an element’s style

We can add or remove any style using the style or className


property of the Element node.
Its usage is shown below to change a node’s background color and
add a three-pixel border.
var commentTag = document.getElementById("specificTag");
commentTag.style.backgroundColour = "#FFFF00";
commentTag.style.borderWidth="3px";

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Changing an element’s style
With class

The className property is normally a better choice, because it


allows the styles to be created outside the code, and thus be
better accessible to designers.
var commentTag = document.getElementById("specificTag");
commentTag.className = "someClassName";
HTML5 introduces the classList element, which allows you to
add, remove, or toggle a CSS class on an element.
label.classList.addClass("someClassName");

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 7 of 8

JAVASCRIPT EVENTS
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
JavaScript Events

A JavaScript event is an action that can be detected by


JavaScript.
We say then that an event is triggered and then it can be
caught by JavaScript functions, which then do something in
response.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


JavaScript Events
A brave new world

In the original JavaScript world, events could be specified


right in the HTML markup with hooks to the JavaScript code
(and still can).
As more powerful frameworks were developed, and website
design and best practices were refined, this original
mechanism was supplanted by the listener approach.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


JavaScript Events
Two approaches

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Inline Event Handler Approach
JavaScript events allow the programmer to react to user
interactions
For example, if you wanted an alert to pop-up when clicking a
<div> you might program:
<div id="example1" onclick="alert('hello')">Click for pop-up</div>
The problem with this type of programming is that the HTML
markup and the corresponding JavaScript logic are woven
together. It does not make use of layers; that is, it does not
separate content from behavior.
The better way to program this is to remove the JavaScript from
the HTML.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Listener Approach
Two ways to set up listeners

the design principle of layers is a proven way of increasing


maintainability and simplifying markup.
The problem with the inline handler approach is that it does
not make use of layers; that is, it does not separate content
from behavior.

only one handler can respond to any given element event.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Listener Approach
Two ways to set up listeners

multiple handlers can be assigned to a single object’s


event.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Listener Approach
Using functions

The above examples simply used the built-in JavaScript alert()


function. What if we wanted to do something more elaborate
when an event is triggered? In such a case, the behavior would
have to be encapsulated within a function, as shown below.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Listener Approach
Anonymous functions

An alternative to that shown in Listing 6.12 is to use


an anonymous function (that is, one without a name),
as shown below.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Event Object

No matter which type of event we encounter, they are all


DOM event objects and the event handlers associated
with them can access and manipulate them.
Typically we see the events passed to the function handler
as a parameter named e.

function someHandler(e) {
// e is the event that triggered this handler.
}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Event Object
Several Options

Bubbles. The bubbles property is a Boolean value. If an event’s


bubbles property is set to true then there must be an event
handler in place to handle the event or it will bubble up to its
parent and trigger an event handler there. If the parent has no
handler it continues to bubble up until it hits the document root,
and then it goes away, unhandled.

Cancelable. The Cancelable property is also a Boolean value that


indicates whether or not the event can be cancelled. If an event
is cancelable, then the default action associated with it can be
canceled. A common example is a user clicking on a link. The
default action is to follow the link and load the new page.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Event Object
Prevent the default behaviour

preventDefault. A cancelable default action for an event can be


stopped using the preventDefault()method as shown in Listing
6.14. This is a common practice when you want to send data
asynchronously when a form is submitted, for example, since the
default event of a form submit click is to post to a new URL (which
causes the browser to refresh the entire page).

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Event Types

There are several classes of event, with several types of event


within each class specified by the W3C:
• mouse events
• keyboard events
• form events
• frame events

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Mouse events

Event Description
onclick The mouse was clicked on an element
ondblclick The mouse was double clicked on an element
onmousedown The mouse was pressed down over an element
onmouseup The mouse was released over an element
onmouseover The mouse was moved (not clicked) over an element
onmouseout The mouse was moved off of an element
onmousemove The mouse was moved while over an element

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Keyboard events
Event Description

onkeydown The user is pressing a key (this happens first)

onkeypress The user presses a key (this happens after onkeydown)

onkeyup The user releases a key that was down (this happens last)

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Keyboard events
Example

<input type="text" id="keyExample">


The input box above, for example, could be listened to
and each key pressed echoed back to the user as an
alert as shown in Listing 6.15.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Form Events
Event Description
onblur A form element has lost focus (that is, control has moved to a different
element, perhaps due to a click or Tab key press.

onchange Some <input>, <textarea> or <select> field had their value change.
This could mean the user typed something, or selected a new choice.

onfocus Complementing the onblur event, this is triggered when an element


gets focus (the user clicks in the field or tabs to it)

onreset HTML forms have the ability to be reset. This event is triggered when
that happens.
onselect When the users selects some text. This is often used to try and prevent
copy/paste.
onsubmit When the form is submitted this event is triggered. We can do some
pre-validation when the user submits the form in JavaScript before
sending the data on to the server.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Form Events
Example

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Frame Events

Frame events are the events related to the browser frame


that contains your web page.
The most important event is the onload event, which tells
us an object is loaded and therefore ready to work with. If
the code attempts to set up a listener on this not-yet-
loaded <div>, then an error will be triggered.
window.onload= function(){
//all JavaScript initialization here.
}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Frame Events
Table of frame events

Event Description

onabort An object was stopped from loading

onerror An object or image did not properly load

onload When a document or object has been loaded

onresize The document view was resized

onscroll The document view was scrolled

onunload The document has unloaded

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Section 8 of 8

FORMS
Randy Connolly and Ricardo Hoar Fundamentals of Web Development
user form input should be validated on both the client side
and the server side.

<form action='login.php' method='post' id='loginForm'>


<input type='text' name='username' id='username'/>
<input type='password' name='password' id='password'/>
<input type='submit'></input>
</form>

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Validating Forms
Form validation is one of the most common applications of
JavaScript.
Writing code to prevalidate forms on the client side will reduce
the number of incorrect submissions, thereby reducing server
load.
Although validation must still happen on the server side,
JavaScript prevalidation is a best practice.
There are a number of common validation activities including
email validation, number validation, and data validation.
In practice regular expressions are used and allow for more
complete and concise scripts to validate particular fields.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Empty Field Validation
A common application of a client-side validation is to
make sure the user entered something into a field.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Empty Field Validation

If you want to ensure a checkbox is ticked, use code like that


below.
var inputField=document.getElementByID("license");
if (inputField.type=="checkbox"){
if (inputField.checked)

//Now we know the box is checked


}

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Number Validation

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


Submitting Forms

Submitting a form using JavaScript requires having a node


variable for the form element. Once the variable, say,
formExample is acquired, one can simply call the submit()
method:
var formExample = document.getElementById("loginForm");
formExample.submit();

This is often done in conjunction with calling preventDefault()


on the onsubmit event.

Randy Connolly and Ricardo Hoar Fundamentals of Web Development


What you Learned
1 What is
JavaScript 2 JavaScript Design

3 Using
JavaScript 4 Syntax

5 JavaScript
Objects 6 The DOM

7 JavaScript
Events 8 Forms

Randy Connolly and Ricardo Hoar Fundamentals of Web Development

You might also like