100% found this document useful (1 vote)
217 views

Chapter 8 Javascript

This document provides an overview of JavaScript and how it can be used in web development. It discusses how JavaScript code can be embedded in HTML pages using <script> tags or external JavaScript files. It explains that JavaScript is an interpreted rather than compiled language, and how this affects how scripts are processed. The document also introduces some important JavaScript concepts like objects, properties, and methods. It provides examples of how JavaScript can be used to dynamically write content to a web page.

Uploaded by

FOO POH YEE
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
217 views

Chapter 8 Javascript

This document provides an overview of JavaScript and how it can be used in web development. It discusses how JavaScript code can be embedded in HTML pages using <script> tags or external JavaScript files. It explains that JavaScript is an interpreted rather than compiled language, and how this affects how scripts are processed. The document also introduces some important JavaScript concepts like objects, properties, and methods. It provides examples of how JavaScript can be used to dynamically write content to a web page.

Uploaded by

FOO POH YEE
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 132

Chapter 8

Working with JavaScript –


Part 1

1
Objectives

•Introducing JavaScript
•Working with Java Script Element
•Writing Output to the Web Page
•Working with Variables and Data
•Working with Dates
•Working with Expressions and Operators

2
Objectives
•Creating JavaScript Functions
•Working with Conditional Statements
•Working with Program Loops
•Using Arrays
•Accessing an External JavaScript File
•Commenting JavaScript Code

3
Introduction to JavaScript
• JavaScript is an interpreted programming
or script language.
• JavaScript is used in Web site date.html
development to:
automatically change a formatted date on
a Web page
cause a linked to page to appear in a
popup window
cause text or a graphic image to change
during a mouse rollover
4
Server-side and Client-side
Programs

5
Server-side and Client-side
Programs
•Server-side Programs pose problems:
must be connected to the Web server to
run the CGI script
only the programmer can create or alter
the script
the Web server’s system administrator can
place limitations on how users access the
script
the system administrator has to be
concerned about users continually accessing
the server and potentially overloading the
system
6
Server-side and Client-side
Programs
•Client-side programs :
solve many of the problems associated with
server-side scripts
computing is distributed over the Web, so that
no one server is overloaded with programming
requests
can be tested locally without first uploading it
to a Web server
are likely to be more responsive to the user
can never completely replace CGI scripts
(Server-side program) 7
The Development of JavaScript
•JavaScript is a subset of Java.
•Differences between Java and
JavaScript:
• Java is a compiled language
• JavaScript is an interpreted language

8
• A compiler is a separate program that converts the entire source program
into machine language before executing it. The machine language version
that results from compiling the procedural language is called the object
program or object code. The compiler stores the object program on storage
media for execution later. While it is compiling the source program into the
object program, the compiler checks the source program for errors. The
compiler then produces a program listing that contains the source code and
a list of any errors. This listing helps the software developer make necessary
changes to the source code and correct errors in the program. Figure 11-19
shows the process of compiling a source program.

• An interpreter, by contrast, translates and executes one instruction at a


time. An interpreter reads an instruction, converts it to one or more
machine language instructions, and then executes those machine language
instructions. It does this all before moving to the next instruction in the
program. Each time the source program runs, the interpreter translates and
executes it, instruction by instruction. An interpreter does not produce an
object program. Figure 11-20 shows the process of interpreting a program.
One advantage of an interpreter is that when it finds errors, it displays
feedback immediately. The software developer can correct any errors
before the interpreter translates the next instruction. The disadvantage is
that interpreted programs do not run as fast as compiled program

9
The Development of JavaScript
• Comparing Java and JavaScript
The Development of JavaScript
• Jscript is a version of JavaScript supported by
Internet Explorer.
• The European Computer Manufacturers
Association (ECMA) develops scripting standards.
The standard is called ECMAScript but browsers still
generally call is JavaScript.
https://www.w3schools.com/js/js_versions.asp

11
Working with Script Element
•The Web browser runs a JavaScript
program when the Web page is first
loaded, or in response to an event.
•A JavaScript program can either be
placed directly in a Web page file or
saved in an external text file.
placing a program in an external file
allows you to hide the program code from
the user
source code placed directly in the HTML
file can be viewed by anyone.
12
Creating the Script Element
•Insert a client-side script in a Web page
using the script element.
•The syntax to embed a script is:
<script type=“mime-type”> <script type=“text/javascript”>
script commands and comments code
</script> </script>

where mime-type is the MIME type of the script


language. To create a script element for
JavaScript, set mime-type to “text/javascript”

13
Demo Webpage
Creating the Script Element
• The syntax to access an external script is:
<script src=“url” type=“mime-type”>
where url is the location of the external file containing the script.
rb_survey.html
<head>
<script src= “tny_script.js” type=“text/javascript”> </script>
</head>
You do not have to include a type attribute for JavaScript files because
browsers assume JavaScript’s MIME type, text/javascript, by default.
The script element can be used with programming languages other than
JavaScript. Other client-side scripting languages are identified by
including the MIME type of the language. For example, the scripting
language VBScript from Microsoft has the MIME type text/vbscript and
can be accessed using the following code:
<script src=“url” type=”text/vbscript”></script>
14
If you don’t want to use an external file, you can create an embedded
script by omitting the src attribute and placing all of the JavaScript
code within the script element as follows
<script type=“text/javascript”> doc_write.html
<html>
code <head>
</script> <script type="text/javascript">
function myFunction()
{
return ("Hello, have a nice day!");
}
</script>

</head>
<body>
<script type="text/javascript">
document.write(myFunction())
</script>
<p>The script in the body section calls a function.</p>
<p>The function returns a text.</p>
</body>
</html>
15
Loading the script Element
• The script element can be placed anywhere within the HTML
document. When the browser encounters a script, it immediately
stops loading the page and begins loading script and then
processing the script commands. Only when the script is
completely processed does the browser continue to load the rest
of the HTML file.

• With larger and more complicated scripts, this loading sequence


can degrade the user’s experience because the page is literally
stalled as it waits for the script to be processed.

16
• You can modify this sequence by adding the async or defer attributes to the script element.
• The async attribute tells the browser to parse/translate the HTML and JavaScript code together, only pausing to
process the script before returning to the HTML file.

• The defer attribute defers script processing


until after the page has been completely
parsed and loaded.

• It is important to note that document objects can be referenced only after the browser has finished parsing the page content. Any
command that references a document object before the browser has parsed the HTML code will result in an error because those
objects do not yet reside in memory. To ensure that an object can be referenced within a JavaScript program, apply the defer attribute
to the script element so that JavaScript code is run only after the page is completed loaded.

17
https://www.w3schools.com/code/tryit.asp?filename=GHT1F3XS99YC
19
In this session, you will use JavaScript to write content into the web page itself. To
do that, you have to work with objects. An object is an entity within the browser or
web page that has properties that define it and methods that can be acted upon it.

For example, a video embedded on a web page is an object and has properties
such as source of the video file or the width and height of the video player. It also
has methods such as playing or pausing the video.
https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_video_js_prop

JavaScript is an object-based language that manipulates an object by changing


one or more of its properties or by applying a method that affects the object’s
behavior within the web page or web browser.

There are four kinds of JavaScript objects: built-in objects that are intrinsic to the
JavaScript language, browser objects that are part of the browser, document
objects that are part of the web document, and customized objects that are
created by the programmer for use in his or her application.
document.write(“welcome to our website”);
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_writeln

https://www.w3schools.com/code/tryit.asp?filename=GHT1F3XS99YC
Object hierarchy
• Browser objects and document objects are organized in hierarchical
structures respectively called the browser object model (BOM) and the
document object model (DOM). Figure 9-12 shows a portion of this
hierarchical structure with the window object, representing the browser
window, as the topmost object in the hierarchy
• The DOM has a hierarchy of elements with the window as the top level
object (most general object to the most specific)
 Objects are items that exist in a
defined space in a Web page.
Each object is identified by an
object name.
 Each object has properties that
describe its appearance, purpose,
or behavior
 An object can have methods,
which are actions that can be
performed with or to it.
window.document.formName 21
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc
_writeln

Writing Output to the Web Page


• An object-oriented programming language writes
the output by manipulating tasks.
• An action you perform on an object is called a
method.
• Examples of writing text to a Web page :
document.write(“Text”); writeln.html
document.writeln(“Text”);
document.write(“<h3>Text</h3>”);
• Note: -
- document.write() : without line breaks
- document.writeln() : with line breaks
22
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc
_writeln

23
8.3 Writing Output to the Web
Page
• JavaScript commands and names are case-sensitive. Example : -
document.write(); ≠ Document.Write();

• JavaScript command lines end with a semicolon to separate it from the


next command line in the program.

24
Working with Variables and Data
• A variable is a named item in a program that stores
information. Example: -
variable
var year;
year = 2003;
document.write(“The year is “ + year);
Output :The year is 2003
• Note:
- The plush symbol(+) is used for text
Concatenation.
- The var is used to declare a variable in JavaScript.

25
https://www.w3schools.com/js/js_hoisting.asp
Declaring a JavaScript Hoisting
Variable
•Any of the following commands is a
legitimate way of creating a variable
named “Month”:
var Month;
Month = “December”;
OR
var Month = “December”;

the first command creates the variable without


assigning it a value, while the second and third
commands both create the variable and assign it a
value
26
Types of Variables
•JavaScript variable types:
Numeric variables (e.g : 10, 2.7)
String variables (e.g : Happy)
Boolean variables (e.g : True / False)
Null variables (e.g: no value at all)
https://www.w3schools.com/js/js_variables.asp

27
Working with Dates
•There are two ways to create a date
object:
variable = new Date(“month, day, year, hours:minutes:seconds”)
or
variable = new Date(“month, day, year, minutes, seconds”)
• Examaple :
var Today = new Date("October 15,2003");
var Today = new Date( );

28
Retrieving the Day Value
• The Today variable has all the date and time information you need.
• JavaScript stores dates and times as the number of milliseconds since
6 p.m on 12/31/1969.
• Use built in JavaScript date methods to do calculations.
var Today = new Date("October 15,2003");
var Today = new Date( );

29
Retrieving the Day Value
•Example of getting the date from date
object:-
var Today = new Date("October 15,2003");
var Today = new Date( );

thisDate = Today.getDate()
thisMonth = Today.getMonth()+1;
thisYear = Today.getFullYear();

30
Retrieving the Year Value var Today = new Date(“April, 8,2006");
thisDate = Today.getDate()
Date Methods thisMonth = Today.getMonth()
+1;
thisYear =
Today.getFullYear();
tny_july.html

New
code
Setting Date and Time Values tny_july.html

33
Chapter 6 Working with Java Script
Working with the Math Object
• Math object: Built-in object used to perform mathematical tasks and store
mathematical values
• Syntax to apply a Math method is tny_july.html

Math.method(expression)
where method is the method applied to a mathematical expression

34
Working with Expressions and
Operators
• Expressions are JavaScript commands that assign
values to variables.
• Expressions are created using variables, values, and
operators (elements that perform actions within
the expression).
• One of the most commonly used operators is the +
operator, which performs the action of adding or
combining two elements.

35
Working with Expressions and Operators

for example, use the plus operator in a


program with the following command:
var ThisMonth = Today.getMonth()+1;

•The + operator belongs to a group of


operators called arithmetic operators, which
perform simple mathematical calculations.

36
Arithmetic Operators
• This figure lists some of the arithmetic operators and gives examples
of how they work.
100%5=0 102%5=2

37
https://www.w3school
Assignment Operators s.com/Js/js_operators
.asp
This figure shows additional assignment operators that
can be used. Assignment operators allow you to create
expressions that are both efficient and compact.

38
Comparison, Logical and Conditional Operators

This figure lists some of the other comparison


operators used in JavaScript

39
Comparison, Logical and
Conditional Operators
This figure lists some of the logical operators used
by JavaScript.

40
Working with Conditional Statements
• Conditional statements are commands that run only
when specific conditions are met.
• Conditional statements require a Boolean expression.

• The following expression will return either true / false :-


var x = 10;
var y = 5;

x < 100; /* True */


y == 20; /* False */
(x < 100) && (y == 20); /* False */

41
Using an If Statements
•The If statement runs a set of
commands if the condition is true.
•The general syntax is:
if (condition) {
JavaScript Commands if true
}
Where condition is Boolean expression. If
condition is true, the command block is
run. If condition is false, the command
block is skipped.
42
Using an If… Else Statements
• To run the If statement for one set of commands if the condition is
true and another set of commands if the condition is false use the
If...Else statement.
• The general syntax is:
if (condition) {
JavaScript Commands if true
} else
JavaScript Commands if false
}

43
Working with Program Loops
•A program loop is a set of instructions
that is executed repeatedly.
Use program loops to configure a group
of commands to be executed a set number
of times.
The loop uses a counter to track the
number of times the command block has
been run.

44
The For Loop Exercise4_for_loop_table.html

Creating a For loop


 Example : - 1 2 4
3
<table border = “2”>
<tr>
<script Type = “Text/javascript”>
var num = Array(1,2,3,4);
for (i= 0 ; i < 4; i++) {
document.write (“<td>” + num[i] + “</td>”);
}
</script>
</tr> Num
</table> i 4 1 2 3 4
Array[0]=1
Array[1]=2
Array[2]=3
45
Array[3]=4
The For Loop row 2 1,1
2,1
1,2 1,3 1,4

Nesting a For loop col 1


<table border = “2”>
<script Type = “Text/javascript”>
for (row = 1 ; row <= 3; row++) {
document.write(“<tr>”)
for (col = 1 ; col <= 4; col++) {
document.write (“<td>” + row + “,” col +
“</td>”);
}
document.write(“</tr”>);
}
</script>
</table>

46
The While Loop
Creating a While loop

num 1

47
The While Loop
Nesting a While loop

48
Using Arrays
• An array is an ordered collection of values referenced by a single variable
name.
var variable = new Array (size);
• The following statement shows an example of declaring an array with 2
elements.
var Cars = new Array(2);
Cars[0] = "Audi";
Cars[1] = "Mercedes";
Or
var Car = new Array(“Audi”, “Mercedes”);

49
Creating a JavaScript Function
 A function is a collection of commands that performs
an action or returns a value
 A function name identifies a function
 Parameters are values used by the function
 The function is executed only when called by another
JavaScript command
function_name(parameter values)

Demo13_Email_functions.html

50
Creating a JavaScript Function
Demo11_function_parameter Demo13_Email_functions.html

51
Creating a Function to Return a Value
 For a function to return a value, it must include a return
statement
function function_name(parameters){
JavaScript commands
return value;
}

Demo11_function_parameter

52
<html>
<head>
<script type="text/javascript">
function product(a,b)
{ return a*b; }
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>

<p>The script in the body section calls a function with two parameters (4 and 3).</p>
<p>The function will return the product of these two parameters.</p>
<form name="cal" id="cal">
<table>
<tr>
<td>Number 1 :</td>
<td><input type="text" name="num1" id="num1" size="10" />
</td>
</tr>
<tr>
<td>Number 2 :</td>
<td><input type="text" name="num2" id="num2" size="10" />
</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Multiply" onclick="document.write(product(document.getElementById('num1').value,
document.getElementById('num2').value))" /></td>
</tr>
</table>
</form>
</body>
</html>

53
ES6 allows function parameters
to have default values. • https://www.w3schools.com/js/tryit.asp?filename=
tryjs_es6_default

54
https://www.w3schools.com/js/js_arrow_function.asp

JavaScript Arrow Function


•Arrow functions were introduced in ES6.
•Arrow functions allow us to write shorter function
syntax:

55
Accessing an External JavaScript File

The code to access an external script file is:
<script src="url" type="mime-type"></script>
 Place all script elements that reference external files in the document head
<script src="rb_formsubmit2.js" defer></script>

56
Commenting Java Script Code
 Comments are important programming practice.
 Helps others to understand code better.
 There are two types of comments:
 Single Line //Single Line Comment
 Multiline

/* Multiline
Comment
Example
*/
HTML comment <!-- comment -- > 57
Debugging Your JavaScript Programs
 Debugging is the process of searching code to locate a
source of trouble.
 There are three types of errors:
 Load-time errors
 Run-time errors
 Logical errors

58
Debugging is the process of locating and fixing a programming error. To debug
a program, you must first determine the type of error present in your code.

• A load-time error occurs when a script is first loaded by a browser. As the


page loads, the browser reads through the code looking for mistakes in
syntax. If a syntax error is uncovered, the browser halts loading the script
before trying to execute it.
• A run-time error occurs after a script has been successfully loaded with no
syntax errors and is being executed by a browser. In a run-time error, the
mistake occurs when the browser cannot complete a line of code. For
example, if a command includes a mathematical expression involving
division by zero (something that is not allowed), the program will fail with a
run-time error even though proper syntax is used. 1/0= ?
• A logical error is free from syntax and executable mistakes, but results in an
incorrect result, such as the wrong name being returned from a database or
an incorrect value being returned from a calculation. A logical error is often
the hardest to fix and will require meticulous tracing of every step of the
code to detect the mistake.

59
Debugging Your JavaScript Programs
 Modular code entails breaking up a program’s different
tasks into smaller, more manageable chunks
 An alert dialog box is a dialog box generated by
JavaScript that displays a text message with an OK
button

alert(text);

60
Debugging Your JavaScript Programs
 Microsoft offers the Microsoft Script Debugger
 Firefox also provides the Firefox Error Console
 Every major browser includes debugging
tools to locate and fix errors in your
JavaScript code. For most browsers, you can
open the debugging tool by pressing the F12
key on your keyboard or by selecting
Developer Tools from the browser menu

61
62
JavaScript: Form Validation
 JavaScript can be used to validate input data in HTML forms
before sending off the content to a server.
 JavaScript is used to provide client-side validation.
 It builds into the Web page form resulting immediate
response to users.
 There are common validations such as Required Fields, E-mail
Validation, etc.
Required Fields is the one that checks if a required field
has been left empty. If the required field is blank, an alert
box alerts a message and the function returns false. If a
value is entered, the function returns true (means that data
is OK):

63
Email validation – is the one that checks if the content has
the general syntax of an email.
This means that the input data must contain at least an @
sign and a dot (.). Also, the @ must not be the first
character of the email address, and the last dot must at
least be one character after the @ sign:

A form validation is a process by which the server on the


browser checks form entries and, where possible, eliminates
errors.

rb_survey.html

64
sample order form.
66
JavaScript HTML DOM Objects
 JavaScript arrange objects in a Document Object Model.
 The HTML DOM is a W3C standard.
 DOM is an interface that permits scripts to access and update
the content, structure and style of the document.
 Every element of the web page can be dynamically updated in
response to input from the user or other programs
 The HTML is platform and language independent. It can be used
by any programming language like java, JavaScript and VBScript

67
Object hierarchy
The DOM has a hierarchy of elements with the window as
the top level object (most general object to the most specific)

 Objects are items that exist in a


defined space in a Web page.
Each object is identified by an
object name.
 Each object has properties that
describe its appearance, purpose,
or behavior
 An object can have methods,
which are actions that can be
performed with or to it.

window.document.formName 68
This figure
shows
that each
field in the
order
form has
been
given a
name.

To refer
to a
particular
field, you
attach the
field
name to
the
JavaScript
reference
for the
form.

69
JavaScript HTML DOM Objects
 There is another way to reference an object and that is with an object
collection. Objects are organized into groups called object collections
 An object collection is an array of all objects of a particular type, such as
all of the hyperlinks for a single document or all of the elements within a
single form.
 An item from an object collection can be referenced in one of three ways:
collection[i]
collection[“name”]
collection.name
 collection is the JavaScript name of the collection
 i is an index number of the item in the collection
 name is the name assigned to the object using the name attribute.
<img src=“tny_logo.jpg” id=”logoImg” name=“logolmg”/>
you can reference that image using any of the following expressions:
document.images[0]
document.images[“logoImg”]
document.images.logoImg 70
71
72
https://www.w3schools.com/code/tryit.asp?filename=GHT1F3XS99YC
This figure
shows
that each
field in the
order
form has
been
given a
name.

To refer
to a
particular
field, you
attach the
field
name to
the
JavaScript
reference
for the
form.

74
Document Objects
 The Document object represents the entire HTML document and can be
used to access all elements in a page.
 The Document object is part of the Window object and is accessed
through the window.document property.
 Document Object Collections

Collection Description
anchor[ ] Returns a reference to all Anchor objects in the
document

forms[ ] Returns a reference to all Form objects in the


document

images[ ] Returns a reference to all Image objects in the


document

links[ ] Returns a reference to all Area and Link objects in the


document
75
76
77
document object model (DOM).
Working with Object Properties

 Each object in JavaScript has properties associated with it. (properties are
object attribute)
 There are several ways of working with properties.
1. the value of a property can be changed
object.property = expression
document.body.style.backgroundColor = “blue"
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_backgroundcolor
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_background

2. store the property’s value in a variable


variable = object.property
PageBackgroundColor =document.body.style.backgroundColor

78
3. test whether the property equals a specified value in an If…Then expression
• A conditional statement changes how the Web page behaves based on the
value of an object property.
• The following JavaScript code shows how you can incorporate object
properties into a simple conditional expression:
if (document.body.style.backgroundColor =="black") {
document.body.style.color ="white";
} else {
document.body.style.color ="black";
}
• Using objects, properties, and conditional statement provides a great deal
of control over the appearance of a Web page.

79
https://www.w3schools.com/code/tryit.asp?filename=GHT1F3XS99YC
81
Document Object Properties
Property Description
body Gives direct access to the <body> element
cookie Sets or returns all cookies associated with the
current document

domain Returns the domain name for the current document

lastModified Returns the date and time a document was last


modified
referrer Returns the URL of the document that loaded the
current document
title Returns the title of the current document
URL Returns the URL of the current document

82
Document Object Method
Method Description
close() Closes an output stream opened with the
document.open() method, and displays the
collected data
getElementsById() Returns a reference to the first object with the
specified id
getElementsByName() Returns a collection of objects with the specified
name
getElementsByTagName() Returns a collection of objects with the specified
tagname
open() Opens a stream to collect the output from any
document.write() or document.writeln() methods
write() Writes HTML expressions or JavaScript code to a
document
writeIn() Identical to the write() method, with the addition of
writing a new line character after each expression

83
The window Object – Open new window
window.open("intro.html"); [OR]
window.open("intro.html", "_blank");
Open [intro.html] in a new tab/window

window.open("intro.html", "_self");

Open [intro.html] in the current tab/window

window.open("intro.html", "intro");

Open [intro.html] in the tab/window named “intro”


- subsequent calls will replace the document in the named tab/window rather
than open new tab/window
JavaScript: Cookies and webstorage
 A cookie is a variable that is stored on the visitor's computer. Each time the
same computer requests a web page with a browser, it will send the cookie
too. With JavaScript, you can both create and retrieve cookie values.
 Examples of cookies:
 Name cookie - The first time a visitor arrives to your web page, he or she must
fill in her/his name. The name is then stored in a cookie. Next time the visitor
arrives at your page, he or she could get a welcome message like "Welcome
John Doe!" The name is retrieved from the stored cookie.
• Password cookie - The first time a visitor arrives to your web page, he or she
must fill in a password. The password is then stored in a cookie. Next time the
visitor arrives at your page, the password is retrieved from the cookie
• Date cookie - The first time a visitor arrives to your web page, the current date
is stored in a cookie. Next time the visitor arrives at your page, he or she could
get a message like "Your last visit was on Tuesday August 11, 2005!" The date
is retrieved from the stored cookie
https://www.w3schools.com/js/js_cookies.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username
https://www.w3schools.com/html/html5_webstorage.asp
85
Working with Object Methods
• Another way to control a Web page is to use methods.
• Methods are either actions that objects perform or actions applied to
objects.
object.method(parameters);
• object is the name of the object
• method is the method to be applied Note quotes: ‘ and “
• parameters are any values used in applying the method to the object

<a href="myfile.htm"
onmouseover="window.alert('Hello');">Hi</a>

An Event JavaScript written 87 87


inside HTML
 This figure lists some additional JavaScript objects and some of
the methods associated with them.
 A more complete list of objects, properties, and methods refer to
text book

88
Managing Events https://www.w3schools.com/code/tryit.asp?filename=G
HT2KJPWIBNM

 An event is a specific action that triggers the browser to run a block of


JavaScript commands.
event handler
 The general syntax is:
< tag onevent = “JavaScript commands;”>

<form>
<input name="colors" type="radio" onclick="document.body.style.backgroundColor ='red';"/>red <br />

<input name="colors" type="radio" onclick=" document.body.style.backgroundColor ='blue';"/>blue <br />


</form>

• This figure shows an example of the onclick event handler used with a collection
of radio buttons.
• When the user clicks a radio button, the click event is initiated and the onclick
event handler instructs the browser to run a JavaScript command to change the
background color of the Web page.
89
90
This figure shows that events often take place in
rapid succession. https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onchang
e
Get & lose focus https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onfocus
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onblur

91 91
This figure describes event handlers that JavaScript provides.

92 92
9.5.1 Working with Event Handlers
Generally, Internet Explorer and Netscape 6.0 can
apply event handlers to most HTML tags.
Versions of Netscape prior to 6.0 apply event handlers
to a smaller number of HTML tags.
Test Web pages with a variety of browsers and
browser versions, especially if the Web page relies on
JavaScript functions to operate correctly.

93 93
https://www.w3schools.com/ta

9.5.2 JS Commands as Hyperlinks gs/tryit.asp?filename=tryhtml5


_a_href_script

 To run a command in response to the click event, an easy way of doing this is to
create a hyperlink around the object to receive the mouse click.
 The syntax for doing this is:
<a href=“javascript:JavaScript commands”>
Hypertext</a>
<!DOCTYPE html>
<html>
<body>
<a href="javascript:alert('Hello World!');">Execute JavaScript</a>
<br/>
</body>
</html>

The above code display “the Hello World” message when the hypertext
“Execute JavaScript” is clicked.
 One advantage of this technique is that you can apply it to objects that might
not support the onclick event handler in all browsers or browser versions.
94
9.5.3 Using the onload Event Handler
 The event handler for loading the Web page is the onload
event handler.
 This handler is associated with the document object and
must be placed in the <body> tag of the HTML file.

function to run
when the page
event handler is loaded by
the browser

<body onload=“startform()”>
<table width=“620” cellpadding=“0”
cellspacing=“5”>
<tr>
95
95
This figure shows that one of the purposes of the startform() function, is to
retrieve the date string and display it in the formdate field of the order
form.
function startform(){
document.order.formdate.value=todaytxt();
}

<body onload="startform()">
<table width="620" cellpadding="0" cellspacing="5">

1 Current
date

96
This figure shows additional properties and methods that can be associated
with fields.

97
Initiating Events and JavaScript
When using JavaScript to initiate an event, you are
instructing the Web page to perform an action that a
user would normally do.
• for example, such as moving the cursor to a specific field in the form

function startform(){
2 document.order.formdate.value=todaytxt();
document.order.product.focus();
}

This figure shows an example of moving the focus to


the product field.

98 98
Creating a Calculated Field
 You can use JavaScript to calculate the cost of a customer’s order based on
product purchased, quantity, sales tax, and shipping costs.
 JavaScript:
• treats the values of input fields as text strings
• does not round off the values to nice digits
• displays calculated values to several digits
 The dollar() function takes a value, n, and rounds it to two digits to the right of
the decimal point.

function calculate(){
var amt1, amt2, amt3, total;
3 amt1 = parseFloat(document.getElementById('Amount1').value);
amt2 = parseFloat(document.getElementById('Amount2').value);
amt3 = parseFloat(document.getElementById('Amount3').value);
total = amt1 + amt2 + amt3;
document.getElementById('totalAmount').value=total.toFixed(2); }
Parses a string and returns a floating point number Calculation 99
99
function calculate(){
var amt1, amt2, amt3, total;
amt1 = parseFloat(document.getElementById('Amount1').value);
amt2 = parseFloat(document.getElementById('Amount2').value);
amt3 = parseFloat(document.getElementById('Amount3').value);
total = amt1 + amt2 + amt3;
document.getElementById('totalAmount').value=total.toFixed(2); }
100
Working with a Selection List
 JavaScript treats a selection list as an array of option values.
 This figure shows the JavaScript object references and property values for
the items in a product selection list. The array of selection options starts
with an index value of 0.

10
1
Working with a Selection List
 There is no value property for the selection list itself, only for the options
within the list.
 The selectedIndex property indicates the index number of the selected option.

function order_price(){
item_index=document.order.product.selectedIndex; //item_index=1
item_value=document.order.product.options[item_index].value; //item_value=19.95
qty_ordered=document.order.qty.selectedIndex; //qty_ordered=10
document.order.sub1.value=dollars(item_value*qty_ordered); // 19.95*10
document.order.sub2.value=dollars(item_value*qty_ordered*0.05); //19.95*10*0.05
total_price();
}

 The index number of the selected item is stored in the item_index variable.
 The item_index variable is then used to determine the value of the selected
item and stores the value in the item_value variable.
 The text of the selected item is stored in the item_text variable. 102
Working with a Selection List
 There is no value property for the selection list itself, only for the options
within the list.
 The selectedIndex property indicates the index number of the selected option.

 The index number of the selected item is stored in the item_index variable.
 The item_index variable is then used to determine the value of the selected
item and stores the value in the item_value variable.
 The text of the selected item is stored in the item_text variable. 103
This figure shows some of the other properties and methods
associated with selection lists and selection options.

104
4
This figure shows the order_price() function.

105
9.8 Working with Radio Buttons
 The JavaScript reference for a radio button is:
document.form.field[i]
• form is the name of the Web page form
• field is the name assigned to the radio button
• i is the index number of specific radio button
 The first radio button has an index value of 0, the second button has an index
value of 1, and so on.
• There is no JavaScript object that refers to the entire collection of radio
buttons; You could use an If…Then statement to test which radio button was
selected.

if(document.order.shipping[0].checked)
{document.order.sub3.value="7.95";}
else if(document.order.shipping[1].checked)
{document.order.sub3.value="9.95";}
else {document.order.sub3.value="12.95";}
106
if(document.order.shipping[0].checked)
Working the { document.order.sub3.value="7.95";}
else if(document.order.shipping[1].checked)
Method

“this” Keyword {document.order.sub3.value="9.95";}


else {document.order.sub3.value="12.95";}

function shipping_price(field) { Method 2


document.order.sub3.value=dollars(field.value);
total_price();
}
<input type="radio" name="shipping" value="7.95" onclick="shipping_price(this)">
Standard (3-5 days): $7.95<br>
<input type="radio" name="shipping" value="9.95" onclick="shipping_price(this)">
Express (2 days): $9.95<br>
<input type="radio" name="shipping" value="12.95" onclick="shipping_price(this)">
Next Day (1 day): $12.95

 The “this” keyword is a JavaScript object name that refers to the currently
selected object.
 Useful in situations where several different objects on the page might access the
same function.
• in that situation, the “this” keyword can pass along information about the
object that initiated the function 107 10
7
This figure describes some of the properties, methods, and
event handlers associated with radio buttons.

108
9.10 Working with Check Boxes
This figure lists some of the properties,
methods, and event handlers of check box
objects.

109 10
9
6 function copy_shipping(){
if(document.order.billcb.checked){
document.order.bname.value=document.order.sname.value;
document.order.bstreet.value=document.order.sstreet.value;
document.order.bcity.value=document.order.scity.value;

document.order.bstate.selectedIndex=document.order.sstate.selectedInd
ex;
document.order.bzip.value=document.order.szip.value;
}
}
<input type="checkbox" name="billcb" onclick="copy_shipping()” >

110
Controlling Form Submission
 When a user completes a form and then clicks the submit
button, a submit event is initiated.
 JavaScript provides the onsubmit event handler that allows
you to run a program in response to this action.
 The submit event is associated with the form object, the
event handler must be placed within the <form> tag.
 The onsubmit event handler must be able to override the
act of submitting the form if the form fails a validation test.

111 11
1
 The syntax for doing this is:
<form onsubmit=“return function();”>

• function is the name of the function that validates


your form
• the function must return a value of true or false
if the value is true, the form is submitted
if the value is false, the submission is canceled, and the
user is returned to the form
• the keyword return in this syntax.
if the return keyword is not included, the browser submits the form
whether or not it passes the validation test.

112
Submitting a Form onsubmmit return checkform.html

 If a condition of the form is not met, the browser should refuse the form
submission and indicate to the user why the form was not submitted.

function checkform() {
function checkform() {
     if (document.myform.age.value =="") {
     if (document.myform.age.value =="") {
              alert("You need to specify an age"); Ne
              alert("You need to specify an age"); ede
              return false;
              return false; d to
br o p
      } else {
      } else { w s r even
            return true; su b e r f t
            return true; mit rom the
      }
      } ting
}} !

Needs to return true or false!

<body>
    <form method="get"  name="myform"  onSubmit="return checkform()" 
For
action="http://www.tarc.edu.my">
assignment
        Age:<input type="text" name="age"/>
        <input type="submit" value="Submit"/>
     </form>                                     

<script 113 11
3
• https://www.w3schools.com/js/js_validation.asp
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>

<h2>JavaScript Validation</h2>

<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">


Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

114
7 <head> <script>

115
This figure shows the code to return the value
of the form_ok variable that indicates whether
or not the form was completed properly.
8

116 11
6
9.13 Creating a Dialog Box
 You may want to use a dialog box to display a message to the user to indicate
that the form was not properly completed.
 JavaScript supports three types of dialog boxes: alert, prompt, and confirm.
• an alert dialog box displays a message, usually alerting the user to a problem.
• the prompt dialog box displays both a message and a text box.
• the confirm dialog box display a message along withOK and Cancel buttons.
• The syntax for creating these dialog boxes is:
alert(“message”);
prompt (“message”, “default”);
confirm (“message”);
• message is the text displayed in the dialog box
• default is the default text for the prompt dialogbox

117
9 <head> <script> checkform()

if(form_ok){
alert("Your order has been submitted");}
else {
if(product_ok==false) alert("Select a product, quantity and
shipping method");
if(shipping_ok==false) alert("Enter a shipping address ");
if(payment_ok==false) alert("Enter a billing address or credit
card");
}

118
10 <body> <table>

<form name="order" method="post" onsubmit="return


checkform()" onreset="location.reload()"
action="Demo10b.htm">

119
Resetting a Form
 When designing a form, it is important to allow the user to reset the
form.
 Resetting a form does not load the page.
 Use JavaScript to reload the page.
• this has the effect of resetting all field values and rerunning the
startform() function that inserts the current date.
• use the location object to reload a Web page
 One of the methods associated with the location object is the
reload()method, which reloads the current page.
 The syntax is simply:
location.reload();
 Use JavaScript to load a different page, the command is:
location=“URL”;
• URL is the address of the Web page you want to display in the
browser
 To control the reset event, use the onreset handler and apply it to the
<form> tag.

120
https://www.w3schools.com/js/js_htmldom_eventlistener.asp
•The addEventListener() method attaches an event handler to the specified element.
•The addEventListener() method attaches an event handler to an element without
overwriting existing event handlers.
•You can add many event handlers to one element.
•You can add many event handlers of the same type to one element, i.e two "click" events.
•You can add event listeners to any DOM object not only HTML elements. i.e the window
object.
•The addEventListener() method makes it easier to control how the event reacts to
bubbling.
•When using the addEventListener() method, the JavaScript is separated from the HTML
markup, for better readability and allows you to add event listeners even when you do not
control the HTML markup.
•You can easily remove an event listener by using the removeEventListener() method.

121
122
<!DOCTYPE html>
<html>
<body>

<p>Click "Try it". Wait 3 seconds, and the page will alert
"Hello".</p>

<button onclick="setTimeout(myFunction, 3000);">Try


it</button>
https://www.w3schools.com/js/tr
<script> yit.asp?filename=tryjs_timing1
function myFunction() {
alert('Hello');
}
</script>

</body>
</html> 123
<!DOCTYPE html>
<!DOCTYPE html> <html>
<html> <body>
<body>
<p>Click the button to wait 3 seconds, then
<p>Click "Try it". Wait 3 seconds, and the page alert "Hello".</p>
will alert "Hello".</p>
<button onclick="myFunction()">Try
<button onclick="setTimeout(myFunction, it</button>
3000);">Try it</button>
<script>
<script> function myFunction() {
function myFunction() { setTimeout(function(){ alert("Hello"); }, 3000);
alert('Hello'); }
} </script>
</script>
</body>
</body> </html>
</html>

Another example :Book return date https://www.w3schools.com/jsref/met_win_settimeout


.asp

1000millisecond =1 second
tny_july.html 124
https://www.w3schools.com/jsref/met_win_cleartimeout.asp

125
a period between
two events or times

https://www.w3schools.com/js
ref/met_win_clearinterval.asp

126
example :count down tny_july.html

Another example
1000millisecond =1 second :Book return date
127
1000millisecond =1 second 128
End

129
ECMAScript 2009 - ES5
•ECMAScript 2009, also known as ES5, was the first major revision
to JavaScript.
•This chapter describes the most important features of ES5.
ES5 Features
•"use strict"
•String[number] access https://www.w3schools.com/js/js_
•String.trim() es5.asp
•Array.isArray()
•Array.forEach()
•Array.map()
•Array.filter()
•Array.reduce()
•Array.every()
•Array.some()
•Array.indexOf()
•Array.lastIndexOf()
•Property getters and setters
•Reserved words as property names
•Object defineProperty()
130
https://www.w3schools.com/js/js_es6.asp#mark_map
• ECMAScript 6 was the second major revision to JavaScript.
• ECMAScript 6 is also known as ES6 and ECMAScript 2015.

New Features in ES6


•The let keyword
•The const keyword
•Arrow Functions
•For/of
•Set Objects
•Classes
•Default Parameters
•Function Rest Parameter
•String.includes()
•String.startsWith()
•String.endsWith()
•Array.find()
•Array.findIndex()
•New Number Properties
•New Number Methods
•New Global Methods
131
https://www.w3schools.com/js/js_2016.asp
New Features in ECMAScript 2016
This chapter introduces the new features in
ECMAScript 2016:
•JavaScript Exponentiation (**)
•JavaScript Exponentiation assignment (**=)
•JavaScript Array.prototype.includes

https://www.w3schools.com/js/js_2017.asp
New Features in ECMAScript 2017
This chapter introduces the new features in
ECMAScript 2017:
•JavaScript String padding
•JavaScript Object.entries
•JavaScript Object.values
132

You might also like