Module 5
Introduction to JavaScript: Functions, DOM, Forms, and Event
Handlers:History of JavaScript, Hello World Web Page, Buttons, Functions,
Variables, Identifiers, Assignment Statements and Objects, Document Object
Model, Forms and How They’re Processed: Client-Side Versus Server-Side, form
Element, Controls, Text Control, Accessing a Form’s Control Values, reset and
focus Methods
• TextBook2: 8.2 to 8.13, 8.15, 8.16
Introduction
• Why Study JavaScript?
• JavaScript is one of the 3 languages all web developers must learn:
• 1. HTML to define the content of web pages.
• 2. CSS to specify the layout of web pages.
• 3. JavaScript to program the behavior of web pages.
• JavaScript has two forms of comments.
• First, whenever two adjacent slashes (//) appear on a line, the rest of the line is considered a comment.
• Second, /* may be used to introduce a comment and */ to terminate it.
8.2 History of JavaScript
• HTML’s first version, designed by Tim Berners-Lee from 1989 to 1991, was fairly static in nature.
• In 1995, the dominant browser manufacturer was Netscape, and one of its employees, Brendan
Eich, thought that it would be useful to add dynamic functionality to web pages.
• So he designed the JavaScript programming language, which adds dynamic functionality to web
pages when used in conjunction with HTML.
• For example, JavaScript provides the ability to update a web page’s content when an event occurs,
such as when a user clicks a button. It also provides the ability to retrieve a user’s input and
process that input.
• It took Eich only 10 days in May 1995 to implement the JavaScript programming language.
• Marc Andreessen, one of Netscape’s founders, originally named the new language Mocha and then
LiveScript.
• But for marketing purposes, Andreessen really wanted the name JavaScript.
• At the time, the software industry was excited about the hot new programming language, Java.
• In December 1995, Andreessen LiveScript’s name was changed to JavaScript.
• Unfortunately, many, many people over the years have made the mistake of assuming that
JavaScript is the same as Java or very close to it.
• In 1996, Netscape submitted JavaScript to the Ecma International standards organization to
promote JavaScript’s influence on all browsers (not just Netscape’s browser).
• Ecma International used JavaScript as the basis for creating the ECMAScript standard.
• ECMAScript now serves as the standard for the interactive programming languages embedded in
all of today’s popular browsers.
8.6 Variables
• Before using a variable in JavaScript code, use var to declare the variable in a declaration statement.
For example: var name, msg;
• In most programming languages, when declaring a variable, type of values must be specified that
the variable will be allowed to hold—numbers, strings, and so on.
• However, with JavaScript, there is no need to specify the variable’s type as part of the declaration.
The variable’s type is determined dynamically by the type of the value that’s assigned into the
variable.
• For example:
var name = "Rama";
var num=20;
• name is string variable , since a string consists of zero or more characters surrounded by a pair of
double quotes (") or a pair of single quotes ('). num is of type number, a number consists of digits
with an optional decimal point.
• JavaScript is known as a loosely typed language, or a dynamically typed language, which means
that declaration of a variable’s data type explicitly is not necessary, can assign different types of
values into a variable at different times during the execution of a program.
8.7 Identifiers
• An identifier is the technical term for a program component’s name—the name of a
function, the name of a variable, and the names of other program components.
Identifiers must consist entirely of letters, digits, dollar signs ($), and/or underscore (_)
characters. The first character must not be a digit.
• Coding conventions suggest to use letters and digits only, not dollar signs or
underscores. All letters should be lowercase except the first letter in the second word,
third word, and so on. That’s referred to as camel case, few examples: firstName,
message, daysInMonth.
• Words that are part of the JavaScript language are known as keywords.
8.8 Assignment Statements and Objects
• All of the elements in a web page are represented as objects. When a browser
loads the Hello web page, the browser software generates objects for the head
element, the body element, the h3 element, and so on. There’s also an object
associated with the entire web page, and that object’s name is document.
• Each object has a set of related properties, plus a set of behaviors.
• A property is an attribute of an object.
• A behavior is a task that the object can perform. The document object contains
properties like the web page’s type.
• <!DOCTYPE html>
• The html value indicates that the document object’s type is HTML5. To access an object’s
property, specify the object name, a dot, and then the property name. So to access the
current web page’s document type, use document for the object name, . for dot, and
doctype for the property.
• In JavaScript (and many other programming languages, as well), an object’s behaviors are
referred to as methods. To retrieve an element, the document object uses its
getElemementById method call in the Example 1 is
• document.getElementById("message");
• Method call includes "message" for its argument. In executing the method call, the
JavaScript engine searches for an element with id="message".
• <h3 id="message">
• To see the traditional first-program greeting, click below.
• </h3>
• So the getElementById method call retrieves that h3 element. The HTML5 standard says that
an id attribute’s value must be unique for a particular web page.
• The getElementById method retrieves the object associated with the h3 element.
• In the displayHello function, getElementById method call is on the right hand side of an
assignment statement, so the method’s returned value (the h3 element’s object) gets assigned
into the variable at the left of the assignment statement. After msg gets the h3 element’s
object, that object gets updated with this assignment statement:
• msg.outerHTML = "<h1>Hello, world!</h1>";
• Note msg.outerHTML. All element objects have an outerHTML property, which stores the
element’s code, including the element’s start and end tags. The msg variable holds the h3
element’s object, so msg.outerHTML holds the h3 element’s code. Assigning <h1>Hello, world!
</h1> to msg.outerHTML causes msg’s code to be replaced with <h1>Hello, world!</h1>. Thus,
when the button is clicked, the original h3 message gets replaced with an h1 “Hello, world!”
message.
8.5 Functions
• syntax for a function definition:
function function-name(zero-or-more-parameters-separated-by-commas)
{
statement-1;
statement-2;
…
last-statement;
}
• And here’s the displayHello function definition from the Hello web page:
• Function call
• <input type="button" value="Click Me!" onclick="displayHello();">
• The parentheses in the function heading are empty because the function call’s parentheses are
empty (the function call was displayHello();). If there are arguments in the function call,then
you’ll normally have the same number of parameters in the function heading—one parameter to
receive each argument’s value.
• The term argument is used for the values in a function call’s parentheses the term parameter for
the associated words in a function definition heading’s parentheses.
• Normally, function definitions should be placed (1) in a script container in the web page’s head
container or (2) in an external JavaScript file.
8.9 Document Object Model
• What is the HTML DOM?
Document Object Model (DOM) is a platform and language-neutral interface that allows programs
and scripts to dynamically access and update the content, structure, and style of a document."
The HTML DOM is a standard object model and programming interface for HTML. It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
• In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.
• HTML DOM methods are actions you can perform (on HTML Elements).
• HTML DOM property is a value that you can get or set(like changing the content of an HTML
element).
• Each node represents either (1) an element, (2) a text item that appears between an element’s start
and end tags, or (3) an attribute within one of the elements.
• The node tree shows blue nodes for each element in the web page code (e.g., head and title).
• It shows yellow nodes for each text item that appears between an element’s start and end tags
(e.g., “Hello”).
• And it shows green nodes for each attribute in the web page document’s elements (e.g., h3’s id
attribute).
• Node at the top of a tree is called the root node.
• The DOM provides different ways to access the nodes in the node tree. There are three common
techniques:
1. Retrieve the node tree’s root by using document (for the document object) in code and then use
the root object as a starting point in traversing down the tree.
2. Retrieve the node that the user just interacted with (e.g. a button that was clicked) and use that
node object as a starting point in traversing up or down the tree.
3. Retrieve a particular element node by calling the document object’s getElementById method with
the element’s id value as an argument.
8.4 Buttons
syntax:
• <input type="button" value="button-label" onclick="click-event-handler">
• Clicking the button is considered to be an event, so the onclick attribute’s JavaScript code is
known as an event handler.
• In the Hello web page source code, note that the onclick attribute’s value is simply
displayHello();. That calls the displayHello function, which is defined in the web page’s script
block.
• The input element’s value attribute specifies the button’s label.
• If you don’t provide a value attribute, the button will have no label.
• If you want a button with no label, rather than just omitting the value attribute, we recommend
that you specify value="". That’s a form of self-documentation, and it makes your code more
understandable.
• Example:
• <input type="button" value="Click Me!" onclick="displayHello();">
• A JavaScript engine is the part of the browser software that runs a web page’s JavaScript. In the
Hello web page, the onclick attribute’s value is JavaScript code that “handles” what’s supposed to
happen when the user clicks the button.
8.3 Hello World Web Page
• Example1:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8">
<title>Hello</title>
<script>
function displayHello()
{
var msg;
msg = document.getElementById("message");
msg.outerHTML = "<h1>Hello, world!</h1>";
}
</script>
</head>
<body>
<h3 id="message">
To see the traditional first-program greeting, click below.
</h3>
<input type="button" value="Click Me!" onclick="displayHello();">
</body>
</html>
• Example 2:
<!DOCTYPE html>
<html>
<head>
<title>
Program 2
</title>
</head>
<body>
<h2>My Second JavaScript Code</h2>
<p id="demo"></p>
<input type="button" value ="Click Me"onclick="document.getElementById('demo').innerHTML = Date()">
</body></html>
• Observe in the above code there is no user defined function. Built in function Date() is called.
• Hence no function is defined in Script tag.
• Initial web page that gets displayed
Following is the Web page that gets displayed when button is clicked
The alert Method
• The alert method opens a dialog window & displays its parameter in the
window ,it also displays a OK button
• The parameter string to alert is not XHTML,it is plain text, so use new lines
rather than <br/>
alert("The sum is:" + sum + "\
n");
The confirm Method
• The confirm methods displays a message provided as a parameter
• The confirm dialog has two buttons: OK and Cancel
• If the user presses OK, true is returned by the method
• If the user presses Cancel, false is returned
var question =
confirm("Do you want to continue this download?");
The prompt Method
• This method displays its string argument in a dialog box
• A second argument provides a default content for the user entry area
• The dialog box has an area for the user to enter text,it also consists of 2 buttons
OK & Cancel.
• The method returns a String with the text entered by the user
name = prompt("What is your name?", "");
Example3: document.getElementById() method that prints cube of the given number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cube of number</title>
<script >
function getcube()
{
var num=document.getElementById("number").value;
alert("Cube of " +num + " is " + (num*num*num) + "\n");
}
</script>
</head>
<body>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
</body>
• External JavaScript file:
• The JavaScript script can be indirectly embedded in an HTML document with the src attribute of a
<script> tag, whose value is the name of a file that contains the script—for example,
• <script src = “message.js" > </script>
• Notice that the script element requires the closing tag, even though it has no content when the src attribute
is included.
• Example4; contents of html file
<html>
<head>
<script src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
• create javascript files similar to external CSS file Note: file with js extension
• contents of message.js
function msg()
{
alert("Hello Javascript");
}
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
The function is invoked (called) when a button is clicked:
Example 5:
<!DOCTYPE html>
<html>
<body>
<h2>Demo JavaScript in Body</h2>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
8.10 Forms and How They’re Processed: Client -Side Versus Server-Side
• A form is a mechanism for grouping input controls (e.g., buttons, text controls, and checkboxes)
within a web page.
• To make forms useful, you need to read the user’s input, process it, and display the results. And to
do all that, you need JavaScript.
• There are two basic strategies for processing a form’s input data.
• The calculations may occur on the client side (on the browser’s computer) or on the server side (on
the web server’s computer).
• With server-side processing, the form input values are transmitted across the Internet to the server
computer.
• The server then does the calculations and transmits the answers back to the client computer.
• The answers are in the form of a new web page or an updated version of the original web page.
• With client-side processing, there’s no need to go back and forth across the Internet with user input
and generated results.
• After the web page downloads, the client computer does all the work.
• Therefore, client-side processing tends to be faster. So normally, you should use client-side
processing for relatively simple web pages.
• There are several reasons why server-side processing is sometimes preferable:
1. When the calculations require a lot of programming code. If client-side processing were used, all the
calculation code would have to be downloaded to the client, and that would slow things down. Slowdowns
can lead to impatient users giving up and going away.
2. When the calculations require the use of large amounts of data, which usually means using a database.
The rationale is basically the same as for the case where there’s lots of programming code. With large
amounts of data, you don’t want to have to download it across the Internet to the browser because that
would slow things down. Therefore, you should keep the data on the server side and do all the processing
there.
3. When the code is proprietary. Proprietary code is code that gives the programmer (or, more often, the
programmer’s company) a competitive advantage. You should keep proprietary code on the server side,
4. When the inputs and/or calculation results need to be shared by other users. In order for the data to
be shared, it needs to be transmitted to the server so it can be later transmitted to other users.
5. When user information needs to be processed securely behind the scenes on the server. For
example, credit card numbers and passwords should be processed on the server side
convert.html
8.11 form Element
• There’s a submit button control at the bottom and other controls above it.
The labels are text prompts that tell the user what to enter in the subsequent controls
• Template for the form element’s syntax:
<form>
label
text-box, list-box, check-box, etc.
label
text-box, list-box, check-box, etc. ...
submit-button
</form>
• The following code implements a form with two text controls and a submit button:
<form>
First Name:
<input type="text" id="first" size="15"><br>
Last Name:
<input type="text" id="last" size="15"><br><br>
<input type="button" value="Generate Email“ onclick="generateEmail(this.form);">
</form>
<p id="email"></p>
function generateEmail(form)
{
document.getElementById("email").innerHTML =
form.elements["first"].value + "." +
form.elements["last"].value + "@gmail.com";
form.reset();
form.elements["first"].focus();
} // end generateEmail}
• Although it’s legal to use input elements—like text controls and buttons—without surrounding
them with a form element, you’ll usually want to use a form.
• Here are some reasons for doing so:
▸ Forms can lead to faster JavaScript processing of the input elements. Understanding why that’s the
case will make sense after we explain the JavaScript code in an upcoming web page later in this
chapter.
▸ Forms provide support for being able to check user input to make sure it follows a particular format.
That’s called input validation, and we’ll spend a considerable amount of time on it in the next chapter.
▸ Forms provide the ability to add a reset button to assign all the form controls to their original values.
To implement a reset button, specify reset for the type attribute, like this:
<input type="reset" value="Reset">
8.12 Controls
• some of the more popular controls and the elements used to implement them.
• Most of the controls use the input element for their implementation. But just to make things
difficult, not all controls use the input element.
• Some important controls use the select and textarea elements.
Input Element Select element
Button pull-down menu
Text control list box
Number
datecolorcontrol.html
Radio button
Password Text area Element
Date Textarea control
color
8.13 Text Control
• A template for the text control’s syntax:
<input type="text" id="text-box-identifier“
placeholder="user-entry-description"
size="box-width" maxlength="maximum-typed-characters">
• The preceding text control template does not include all the attributes for a text control—just the
more important ones.
• An example text control code fragment:
<input type="text" id="ssn"
placeholder="#########" size="9" maxlength="9">
Attributes
Text Control Attributes
type Id placeholder size maxlength value autofocus disabled readonly
• The default value for the type attribute is text, so if you omit the type attribute, you’ll get
a text control, recommend that you always include type="text" for your text controls.
• The id attribute’s value serves as an identifier for the text control, so it can be accessed
with JavaScript. Previously, in the Hello web page, we used an h3 element’s id value and
called getElementById to retrieve the object associated with the h3 element.
• In an upcoming example, we’ll do the same thing using a text control’s id value.
• The placeholder attribute provides a word or a short description that helps the user to
know what to enter into the text control. When the page loads, the browser puts the
placeholder’s value in the text control. As soon as the user enters a character into the text
control, the entire placeholder value disappears.
• The size attribute specifies the text control’s width, where the width value is an integer
that approximates the number of average-size characters that can fit in the box. So
size="5" means approximately 5 characters could display in the box simultaneously. The
default size is 20.
• The maxlength attribute specifies the maximum number of characters that can be entered
in the box. By default, an unlimited number of characters is allowed. Entries that exceed
the box’s width cause input scrolling to occur
• The value attribute specifies an initial value for the text control. The value attribute’s value is treated as user
input. If the user wants a different input, the user must first delete the value attribute’s value. If the user does
nothing and there’s JavaScript code that retrieves the user input, it gets the value attribute’s value by default.
• The autofocus attribute specifies that after the page has loaded, the browser engine positions the cursor in
the text control. To achieve autofocus, specify autofocus by itself. As you may recall, when you specify an
attribute by itself, that’s known as an empty attribute.
• The disabled attribute specifies that the text control cannot receive the focus, and, therefore, the user cannot
copy or edit the text control’s value. To disable a control, specify disabled by itself.
• The readonly attribute specifies that the user can highlight the control’s value and copy it, but the user cannot
edit it. To make a control read-only, specify readonly by itself.
• For disabled and read-only text controls, the only way to change their values is to use JavaScript assignment
statement
8.15 Accessing a Form’s Control Values
• To receive the form object passed to the generateEmail function, there’s a form parameter in the function’s
heading, as you can see here:
function generateEmail(form)
• Within the generateEmail function body, we use the form parameter to retrieve the text control user inputs.
Here’s the code for retrieving the user input from the first-name text control:
form.elements["first"].value
• To access the controls that are within a form, we use the form object’s elements property.
• The elements property holds a collection of controls, where a collection is a group of items that are of the same
type.
• To access a control within the elements collection, you put quotes around the control’s id value and surround
the quoted value with []’s.
• As an alternative to using form.elements["first"], you can use form["first"].
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Email Address Generator</title>
<script>
// This function generates an email address.
function generateEmail(form) {
document.getElementById("email").innerHTML = form.elements["first"].value + "."
+form.elements["last"].value + "@park.edu";
form.reset();
form.elements["first"].focus();
} // end generateEmail
</script>
</head>
JavaScript Object Properties and HTML Element Attributes
• In the form.elements["first"].value code fragment shown in the previous section, the value property
returns the text control’s user-entered value.
• If there’s no user entry, then the value of the text control’s value attribute is returned.
• If there’s no user entry and there’s also no value attribute, then the value property holds the empty string
by default.
• HTML attributes use all lowercase, whereas JavaScript properties use camel case, which means the two-
word properties are spelled maxLength and readOnly.
• Get used to that weirdness—use all lowercase for HTML attributes, but camel case for JavaScript
properties.
• JavaScript is case sensitive, so you must use camel case for your code to work.
• HTML is not case sensitive, but you should use all lowercase in order to exhibit proper style.
Control Elements’ innerHTML Property
• In the Email Address Generator web page’s generateEmail function, the goal is to update the following
p element by replacing its empty content with a generated email address:
<p id="email"></p>
• To do that, we retrieve the p element’s object and then use its innerHTML property, like this:
document.getElementById("email").innerHTML
• Remember the outerHTML property? It accesses the control element’s code, including its start and end
tags. The innerHTML property accesses the content within the control element’s code, not including its
start and end tags.
• In the generateEmail function, here’s the assignment statement that uses innerHTML to update the
p element with a generated email address:
document.getElementById("email").innerHTML = form.elements["first"].value + "." +
form.elements["last"].value + "@park.edu";
• To connect a string to something else (e.g., another string, a number), you need to use the
concatenation operator, +.
• The resulting connected value forms a string.
• So in the preceding assignment statement, the three concatenation operations form a single string,
and that string gets assigned into the innerHTML part of the retrieved p element.
8.16 reset and focus Methods
• The last two lines in the generateEmail function. Here are those lines:
form.reset();
form.elements["first"].focus();
• The form object’s reset method reassigns the form’s controls to their original values. Because the
Email Address Generator web page has no value attributes for its text controls, the reset method
call assigns empty strings to the text controls, thereby blanking them out.
• When an element object calls the focus method, the browser puts the focus on the element’s
control if it’s possible to do so. For text control elements, like the first-name text control retrieved
in the preceding code, putting the focus on it means the browser positions the cursor in the text
control.