Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
50 views

JS&HTML5 - Develop Web Application_sg

The document is a student guide for a course on developing web applications using JavaScript and HTML5, published by Oracle. It outlines the course structure, objectives, and various topics covered, including web application essentials, JavaScript fundamentals, and the integration of HTML5 with JavaScript. The guide emphasizes the proprietary nature of the content and includes a disclaimer regarding its use and distribution.

Uploaded by

Boban Vasiljevic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

JS&HTML5 - Develop Web Application_sg

The document is a student guide for a course on developing web applications using JavaScript and HTML5, published by Oracle. It outlines the course structure, objectives, and various topics covered, including web application essentials, JavaScript fundamentals, and the integration of HTML5 with JavaScript. The guide emphasizes the proprietary nature of the content and includes a disclaimer regarding its use and distribution.

Uploaded by

Boban Vasiljevic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 496

Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
i ce
b l el
fe ra
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
uksa
n V
a
Mil
JavaScript and HTML5: Develop
Web Applications
Student Guide
D84842GC10
Edition 1.0 | Dec 2014 | D88938

Learn more from Oracle University at oracle.com/education/


Authors Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Eduardo Moranchel Disclaimer


Edgar Martinez This document contains proprietary information and is protected by copyright and other intellectual
property laws. You may copy and print this document solely for your own use in an Oracle training
course. The document may not be modified or altered in any way. Except where your use
Technical Contributors & constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print,
Reviewers display, perform, reproduce, publish, license, post, transmit, or distribute this document in whole or
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

in part without the express authorization of Oracle.


Michael Williams
Girija C The information contained in this document is subject to change without notice. If you find any
problems in the document, please report them in writing to: Oracle University, 500 Oracle
Eric Jendrock Parkway, Redwood Shores, California 94065 USA. This document is not warranted to be error-
Sebastien Colas free.
Veerabhadra Rao Putrevu Restricted Rights Notice
Iris Li
Glenn Stokol If this documentation is delivered to the United States Government or anyone using the
documentation on behalf of the United States Government, the following notice is applicable:
n s e
U.S. GOVERNMENT RIGHTS
ice
Graphic Editors
James Hans b l el
The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose
these training materials are restricted by the terms of the applicable Oracle license agreement
and/or the applicable U.S. Government contract.
fe r a
Maheshwari Krishnamurthy
a n s
Trademark Notice
n - tr
Editors o
an
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be
trademarks of their respective owners.
Anwesha Ray
h s
a deฺ
Raj Kumar )
ฺrs t Gui
Vijayalakshmi Narasimhan s
@ em uden
a n S t
Publishers s
uk e thi s
Jayanthy Keshavamurthy ฺ v
i
Michael Sebastian Almeida
m lan to us
Sujatha Nagendran
(
ks a
V u
M li an
Contents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

1 Introduction
About This Course 1-2
Audience 1-3
Prerequisites 1-4
Course Objectives 1-5
Self Introduction 1-7
n s e
Web Applications 1-8
i ce
Course Road Map 1-9
b l el
Schedule 1-10 fer a
a n s
Lesson Layout 1-14
n -tr
Lecture 1-15 o
The JSConsole 1-16
s an
) h a deฺ
ฺrs t Gui
JSConsole Tutorial 1-17
JSConsole Overview 1-18 s
Practice 1: Overview 1-20
@ em uden
a n S t
Assignments 1-21 s
uk e thi s
ฺ v
Course Environment 1-22
an s
n (mil to u
Demo: Using Your Classroom Computer 1-23
Summary 1-24
u ksa
Self-Study Assignment 1-25
n V
a
Mil 2 Web Application Essentials
Course Road Map 2-2
Objectives 2-3
Topics 2-4
Web Servers 2-5
Web Architecture 2-6
How Web Servers Work 2-7
What Is a Client? 2-9
HTTP Protocol 2-10
HTTP Request 2-11
HTTP Request: URL 2-12
HTTP Response 2-13
Response Bodies 2-14
Web Applications 2-15

iii
Web Application Structure 2-17
Website Versus Web Application 2-18
The Server Side Web Application 2-19
Creating Web Applications 2-20
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Creating HTML5 Applications in NetBeans8 2-21


Running the Application 2-22
Application Files 2-23
URL 2-24
HTML Files 2-25
HTML File Structure 2-26
HTML Tag Scope 2-29
n s e
HTML Head 2-30
i ce
HTML Body 2-31
b l el
HTML Style (Embedded CSS) 2-32
fer a
HTML JavaScript (Embedded JS) 2-33
a n s
The Application in Action 2-34 n -tr
o
CSS Files 2-36
s an
JS Files 2-37
) h a deฺ
Resource Hyperlinking 2-38
s ฺrs t Gui
Absolute Paths 2-39
@ em uden
Relative Paths 2-40 a n S t
s
uk e thi
Document Navigation 2-43 s
ฺ v
an s
mil to u
Example: Web Application 2-44
(
Development Tools 2-45
n
u ksa
NetBeans IDE 2-46

n V HTML5 Projects 2-47


a
Mil NetBeans IDE Elements 2-48
Running Applications 2-49
Browser Development Tools 2-50
Where Can I Learn More? 2-51
Summary 2-52
Practice 2: Overview 2-53
Self-Study Research Material 2-54
Self-Study Assignment 2-55

3 JavaScript Fundamentals
Course Road Map 3-2
Objectives 3-3
Topics 3-4
Comparing JavaScript and Java 3-5
Examining the Grammar of JavaScript 3-6

iv
Topics 3-11
Types 3-12
Declaring a Variable 3-13
Example: Variables and Types 3-14
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Topics 3-15
Creating an Array and an Object 3-16
Accessing an Array and an Object 3-17
Creating and Calling a Function 3-18
Working with Operators 3-19
Operators 3-20
Special Operators 3-22
n s e
Example: Expressions and Operators 3-24
i ce
Topics 3-25
b l el
Writing Statements 3-26
fer a
Statements 3-30
a n s
while Loop 3-31 n -tr
o
for Loop 3-32
s an
Example: Statements and Loops 3-33
) h a deฺ
Topics 3-34
s ฺrs t Gui
Creating Objects 3-35
@ em uden
a n S t
Accessing Object Properties 3-38
s
uk e thi s
Working with Object Properties 3-39
ฺ v
an s
mil to u
Accessing Object Properties 3-40
(
Object Methods 3-41
n
uksaExample: Objects 3-42

n V Topics 3-43
a
Mil Creating Arrays 3-44
Accessing Array Elements 3-45
Multidimensional Arrays 3-46
Example: Arrays 3-47
Topics 3-48
Defining Functions 3-49
Anonymous Functions 3-50
Calling a Function 3-51
Recursion 3-53
Scopes 3-54
Example: Functions 3-55
Where Can I Learn More? 3-56
Summary 3-57
Practice 3: Overview 3-58

v
4 Combining HTML5 and JavaScript in Web Applications
Course Road Map 4-2
Objectives 4-3
Topics 4-4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

HTML5 Documents 4-5


HTML5 Sections 4-7
Example: HTML5 Document Sections 4-9
Topics 4-10
Reading Data from HTML5 Forms 4-11
The form Elements 4-12
input Attributes 4-15
n s e
Validating HTML5 Form Input 4-16
i ce
Sending Data from Forms 4-17
b l el
Examples: HTML5 Forms 4-18
fer a
Topics 4-19
a n s
Controlling HTML5 Events with JavaScript 4-20 n - tr
o
Example: HTML5 Events 4-22
s an
Topics 4-23
) h a deฺ
DOM Tree 4-24
s ฺrs t Gui
DOM Tree Nodes 4-26
@ em uden
The Node Object 4-27 a n S t
Node Names 4-28
s
uk e thi s
ฺ v
an s
mil to u
Node Types 4-30
(
The Element Node 4-31
n
u ksa
The document Object 4-32

n V Other Element Nodes 4-33


a
Mil Accessing and Manipulating Elements 4-35
Example: DOM Manipulation 4-37
Where Can I Learn More? 4-38
Summary 4-39
Practice 4: Overview 4-40

5 The JavaScript API


Course Road Map 5-2
Objectives 5-3
Topics 5-4
The JavaScript API 5-6
Parsing Numbers 5-7
Adding Events to DOM 5-8
Number Parsing and Output 5-9
Tip Calculator 5-10

vi
Tip Calculator Logic 5-11
Number.toLocaleString() 5-12
Intl.NumberFormat 5-13
HTML5 Number Input and JavaScript 5-14
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Example: Parsing Numbers 5-15


Topics 5-16
Decoding and Encoding URI 5-17
Example: URL Encoding 5-18
Topics 5-19
String Creation 5-20
String Manipulation 5-21
n s e
Validating and Parsing String Values 5-23
i ce
Splitting the String 5-24
b l el
Topics 5-25
fer a
JavaScript Dates 5-26
a n s
Date String Examples 5-27 n - tr
o
Date Object 5-28
s an
Modifying a Date 5-29
) h a deฺ
Date Operations 5-30
s ฺrs t Gui
em uden
Example: JavaScript Dates 5-31
@
a n S
Reading and Parsing Dates 5-32 t
s
uk e thi s
Exercise: JavaScript String Manipulation 5-33
ฺ v
an s
mil to u
Solution: JavaScript String Manipulation 5-34
(
Topics 5-35
n
uksaRegular Expressions 5-36

n V Sample Regular Expression 5-37


a
Mil Submatched Parentheses Expressions 5-39
Regular Expression Methods 5-40
String RegExp Methods 5-41
RegExp Example 5-42
Example: JavaScript Regular Expressions 5-43
Topics 5-44
JavaScript Arrays as Collections 5-45
Array Methods 5-46
Array.Splice() 5-48
Array.join() 5-49
Array.indexOf() 5-50
Reading and Parsing HTML Lists with JS Arrays 5-51
Example: JavaScript Arrays 5-52
Exercise: JavaScript String Manipulation 5-53
Solution: JavaScript Arrays 5-54

vii
Topics 5-55
JavaScript Objects 5-56
Static Object Methods 5-57
Prototypes 5-58
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Object Methods 5-59


ToString Object Method 5-60
Example: JavaScript Object Methods 5-61
Where Can I Learn More? 5-62
Summary 5-63
Practice 5: Overview 5-64
Assignment Overview 5-65
n s e
i ce
6 Web Application Data
b l el
Course Road Map 6-2
fer a
Objectives 6-3
a n s
Topics 6-4 n -tr
o
JSON 6-6
s an
JSON Strings 6-7
) h a deฺ
Converting to Strings 6-8
s ฺrs t Gui
em uden
Converting Strings to Objects 6-9
@
Exercise 6-10 a n S t
Topics 6-11
s
uk e thi s
ฺ v
an s
mil to u
JavaScript Sandbox 6-12
(
Sandbox Trade-Offs 6-13
n
u ksa
Web Features 6-14

n V Application Data 6-15


a
Mil Topics 6-16
Cookies 6-17
Cookie API 6-18
Using Cookies 6-19
Example: JavaScript Cookies 6-20
Topics 6-21
Local Storage 6-22
Using Local Storage 6-23
Local Storage + JSON 6-24
Exercise 6-25
Where Can I Learn More? 6-26
Summary 6-27
Practice 6: Overview 6-28

viii
7 Style Applications Using CSS3 and JavaScript
Course Road Map 7-2
Objectives 7-3
Topics 7-4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Cascading Style Sheets (CSS) 7-5


Adding CSS to HTML 7-7
Selectors 7-10
Combinators 7-12
Attribute Selectors 7-14
Pseudo-Class Selectors 7-16
Pseudo-Element Selectors 7-17
n s e
Adding Dynamic Styles to Elements 7-18
i ce
CSS3 Properties: Fonts 7-19
b l el
CSS3 Properties: Colors 7-21
fer a
CSS Box Model 7-22
a n s
Display, Alignment, and Position 7-24 n -tr
o
Example: Box Model 7-26
s an
Vendor Prefixes 7-27
) h a deฺ
Topics 7-28
s ฺrs t Gui
Media Queries 7-29
@ em uden
a n
Example: Media Queries 7-32 S t
Topics 7-33
s
uk e thi s
ฺ v
an s
mil to u
Multicolumn 7-34
(
Example: Multicolumn 7-35
n
u ksa
Topics 7-36

n V Modifying Styles with JavaScript 7-37


a
Mil Where Can I Learn More? 7-38
Summary 7-39
Practice 7: Overview 7-40

8 Advanced JavaScript
Course Road Map 8-2
Objectives 8-3
Topics 8-4
JavaScript Functions as Values 8-6
JavaScript Function: this Reference 8-7
Function Methods 8-8
Function Default Value 8-10
Callbacks 8-11
Caution 8-13
JavaScript Functions and Default Values 8-14

ix
JavaScript Array Extended API 8-15
JavaScript Array Method Chaining 8-19
Example: Array Extended API 8-20
Exercise 8-21
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Function Scope 8-22


Function Scope and this Reference 8-23
Overriding Variables 8-24
Scopes and Variables 8-25
Closures 8-26
Closures and Variables 8-27
Example: Closures 8-28
n s e
Private Scope with Closures 8-29
i ce
Example: Private Scope 8-31
b l el
Returning Functions 8-32
fer a
Example: Returning Functions 8-33
a n s
Closures and Loops 8-34 n -tr
o
Anonymous Functions 8-35
s an
Loops with Anonymous Functions 8-36
) h a deฺ
Example: Loops with Closures 8-37
s ฺrs t Gui
Copying Values 8-38
@ em uden
a n S
JavaScript Module Pattern 8-39 t
s
uk e thi
Using Modules 8-40 s
ฺ v
an s
mil to u
Example: Modules 8-41
(
Topics 8-42
n
uksaJavaScript Prototypes 8-43

n V Prototype Functions 8-44


a
Mil Prototype Dynamic Object Modification 8-45
Prototype Chain 8-46
Example: Prototypes 8-47
Topics 8-48
HTML 5 Drag and Drop 8-49
The Drag-and-Drop Process 8-50
Drag Start 8-51
Drag Over 8-52
Drop 8-53
Example: Drag-and-Drop 8-54
Topics 8-55
Delayed Functions 8-56
Interval Functions 8-57
Canceling Intervals and Timeouts 8-58
Example: Timeouts and Intervals 8-59

x
JavaScript Concurrency 8-60
JavaScript Workers 8-61
Using Workers 8-62
Example: Workers 8-63
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Topics 8-64
HTML5 Canvas 8-65
Painting the Canvas 8-66
Canvas Space 8-67
Canvas Strokes 8-68
Canvas Fills 8-69
Canvas Text 8-70
n s e
Paths and Strokes 8-71
i ce
Drawing Paths with Lines 8-72
b l el
Path Curves 8-73
fer a
Shapes 8-74
a n s
Painting Images 8-75 n -tr
o
Example: HTML5 Canvas 8-76
s an
Where Can I Learn More? 8-77
) h a deฺ
Summary 8-78
s ฺrs t Gui
Practice 8: Overview 8-79
@ em uden
a n S t
9 AJAX and WebSocket
s
uk e thi s
Course Roadla
ฺ v
n 9-2us
i Map
( 9-3 to
m
Objectives
n
sa 9-4
VukTopics
an
Dynamic Data with JavaScript 9-6

Mil The Request 9-7


Server Side Processing 9-8
Response 9-9
Topics 9-10
Asynchronous JavaScript and XML 9-11
AJAX and XML 9-12
AJAX and Compatibility 9-13
Synchronous AJAX 9-14
Asynchronous AJAX 9-15
Handling AJAX Responses 9-16
Exercise: AJAX 9-17
Topics 9-18
Representational State Transfer 9-19
REST on the Web 9-20
Practical REST 9-21

xi
Practical Rest 9-23
REST in Action 9-24
HTTP Methods 9-25
RESTful URI 9-26
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Example: REST and AJAX 9-27


Topics 9-28
AJAX Security Concerns 9-29
A Basic AJAX Attack 9-30
JavaScript 9-31
Trusted Servers, Untrusted Data 9-32
Security Measures 9-33
n s e
Cross-Site Scripting (XSS) 9-34
i ce
Topics 9-35
b l el
WebSocket 9-36
fer a
HTTP Push Techniques Versus WebSocket 9-37
a n s
WebSocket Versus Polling 9-39 n -tr
o
Implementing WebSocket in JavaScript 9-40
s an
A WebSocket Example 9-41
) h a deฺ
Example: WebSocket 9-42
s ฺrs t Gui
em uden
When to Use WebSocket and AJAX? 9-43
@
Topics 9-44 a n S t
s
uk e thi s
The Java EE 7 Environment 9-45
ฺ v
an s
mil to u
Java EE 7 Application Server 9-46
(
Java EE 7 Technologies 9-47
n
uksaWhere Can I Learn More? 9-48

n V Summary 9-49
a
Mil Practice 9: Overview 9-50

10 Developing Applications with JQuery


Setting Tag Attributes 10-11
Traversing DOM Elements 10-12
DOM Element Methods 10-14
Example: jQuery Selectors 10-15
Topics 10-16
Handling Events in jQuery 10-17
Example: jQuery Events 10-19
Topics 10-20
Applying Effects 10-21
Custom Effects 10-23
Example: jQuery Effects 10-26
Topics 10-27

xii
AJAX 10-28
Handling Server Response 10-29
Example: jQuery Ajax 10-32
Topics 10-33
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Adding jQuery UI to Your Project 10-34


jQuery UI Components 10-35
Where Can I Learn More? 10-36
Summary 10-37
Course Road Map 10-38

n s e
i ce
b l el
fer a
a n s
n -tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
uksa
n V
a
Mil

xiii
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Mil
an V u
ksa
n(
an ฺ v
mil to u
s
s
a n @
uk e thi s S t
s
)
em uden
h s
ฺrs t Gui
an
o
a deฺ
trn -
a n s fe
r
a b l el
i
ce n s e
1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Introduction ice n s e
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
About This Course
JavaScript and HTML5: Developing Web Applications
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s course:
Duringkthis
u
•V You write JavaScript code to add logic to your applications
l a n
Mi • You create user interfaces by using HTML5 and CSS
• You create and maintain web applications

JavaScript and HTML5: Develop Web Applications 1 - 2


Audience

• Programmers who want to build web


applications by using JavaScript,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

HTML5, and CSS

• Web designers
g who want to expand
p
their skill set to create interactive web
pages by using JavaScript
n s e
• Java Programmers who want to start ice
developing web applications by using b l el
fe r a
the Java EE platform
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks is aimed at anybody who is interested in building web applications that run on a
This course
u
V browser and that can be deployed on any web server or even be distributed stand alone.
web
l a n
Mi The course is targeted at web designers, software developers, technical writers, testers, and
individuals with some technical expertise or background.

JavaScript and HTML5: Develop Web Applications 1 - 3


Prerequisites

To successfully complete this course, you must have:


• Basic programming experience
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Basic web knowledge

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 4


Course Objectives

After completing this course, you should be able to:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Build web applications by using JavaScript, HTML, and CSS


– Code application logic with JavaScript
to create interactive content

– Design HTML5 documents to


present data and display user n s e
ice
interfaces
b l el
fe r a
– Add CSS to documents to
a n s
create appealing designs for n - tr
o
your web applications
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksweb applications by using JavaScript, HTML, and CSS, you would need to:
To build
u
an •V Use the browser’s tools to debug and inspect the web applications and their styles
Mil • Code application logic by using JavaScript to control user interactions and display data
• Create applications with multiple HTML5 pages, with navigation and HTML5 Forms to
send data to services
• Create design templates and standards by using CSS and JavaScript that adapt to
different devices, including mobile, with Media Queries and Responsive Design
• Read and validate data from HTML5 forms by using JavaScript
• Use the JavaScript API to parse
parse, modify
modify, and validate data

JavaScript and HTML5: Develop Web Applications 1 - 5


• Use JavaScript to add interactivity in HTML5 by using events and Document Object
Model (DOM) modification
• Use the JavaScript Object Notation (JSON) to store and send JavaScript Object data to
services,, local storage,
g , or across different pages
p g and HTML5 elements
• Draw on HTML5 canvas by using JavaScript
• Use the HTML5 local storage to store user data in web applications
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Create JavaScript code to retrieve and display dynamic data from REpresentational
State Transfer (REST) services by using AJAX
• Create JavaScript code to interact with WebSocket for real-time communication

n s e
i ce
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 6


Self Introduction

Share something about yourself.


• What is your name?
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• What do you do for a living, and where do you work?


• Which is the most interesting website that you have come
across?
• What interests you the most about web applications?
n s e
• What are your expectations from this course? ce
el i
a b l
fe r
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 7


Web Applications

Web applications come in many forms:


• Simple static web pages
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Single page applications


• Animated pages with JavaScript
• Interactive pages
• HTML5 games
n s e
• Forms to request user data ice
Examples of a web application: b l el
fe r a
• Weather
W th web b page a n s
n - tr
• The Oracle web portal o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 8


Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
s an Day

) h a deฺ
s ฺrs t Gui Hands-On Practice

@ em uden Lecture

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 9


Schedule

• Day 1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Lesson 1: Introduction
– Assignment: Environment Setup
– Lesson 2: Web Application
pp Essentials
– Demo: Web Applications
– Practice: Building Web Applications
Assignment: Practicing with browser’s tools n s e
ce

– Lesson 3: The JavaScript programming language el i


a b l
– Practice: Using Unit Testing with JavaScript fe r
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 10


Schedule

• Day 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Lesson 4: Combining HTML5 and


JavaScript in Web Applications
— Practice: Modifying DOM with JavaScript
– Lesson
L 5
5: Th
The JJavaScript
S i t API
— Practice: Creating a bill and tip calculator
— Assignment: Reviewing the JavaScript APIs
n s e
– Lesson 6: Application Data ice
Practice: Saving user information for the bill and tip calculator b l el

f e ra
t r a ns
o n -
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 1 - 11


Schedule

• Day 3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Lesson 7: Style applications using CSS3


and JavaScript
— Practice: Styling Elements with CSS3
– Lesson
L 8
8: Ad
Advanced
d JJavaScript
S i t
— Practice: Creating an HTML5 canvas application

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 12


Schedule

• Day 4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Lesson 9: Dynamic Data with JavaScript


using AJAX and WebSocket
— Practice: Creating a dynamic AJAX application
— P ti
Practice: C
Creating
ti a W WebSocket
bS k t game

– Lesson 10: Developing Applications with JQuery s e


ce n
el i
a b l
fe r
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 13


Lesson Layout

Lecture
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Slides Examples Exercises

Practice
Lab Activities n s e
ice
b l el
fe r a
a n s
Self-Study o n -tr
s an
Assignments h a Research
eฺ
) i d
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 1 - 14


Lecture

Slides
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Contain theory, examples, concepts, and notes

Examples
• Include demos and code samples
• Run in the JSConsole application n s e
ice
b l el
Exercises fe r a
a n s
• Include small assignments
o n -tr
an
• Are to be edited and run by using the JSConsole
s
application
)ha id eฺ
ฺ r s u
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 1 - 15


The JSConsole

• This is the web application that is used in the course to run


and edit exercises and demos.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• In your lab machines, go to: http://localhost:8080/JSConsole.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks JSConsole to edit and run simple demos and exercises directly from your browser.
• Use
u
•V If you see a JSConsole icon, it means that there is an example or exercise in
an
Mil JSCo so e
JSConsole.
• On the JSConsole home page, you see all examples listed, for each lesson.
• To edit an example, click the Pencil button.
• To run an example in a separate window, click the Run button.
• If an example becomes unresponsive because of invalid JavaScript code, such as
infinite loops, click the Revert button on the extreme right of the example that has
become unresponsive.
p

JavaScript and HTML5: Develop Web Applications 1 - 16


JSConsole Tutorial

The JSConsole examples in this lesson focus on showing you the


different modes that JSConsole has:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

JavaScript Examples
Example of a JavaScript only environment

JavaScript Editor
Review and edit JavaScript code.
Try this in
Web Editor JSConsole n s e
ice
Edit web pages with multiple files.

b l el
Test Editor fe r a
S l JJavaScript
Solve S i t challenges
h ll iin JSConsole.
JSC l
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s machine, open your browser, navigate to http://localhost:8080/JSConsole, and go
In yourklab
u
V each of the examples in this lesson by clicking the Pencil icon.
nthrough
a Each example shows how to use the JSConsole application.
Mil
If you prefer to edit the examples and exercises outside JSConsole, you can find the source
files under the /home/oracle/demos/local folder. You can open the HTML files in your browser,
edit them in any text editor, or even open the folder as a new Web Application by using
NetBeans 8.
Be aware that JavaScript tests will not run outside JSConsole. You must run such exercises
in JSConsole, but you can modify files in any other editor.
Be careful when editing demos and exercises outside JSConsole. If you were to render a file
or example unusable, delete the file or folder, open a browser, and navigate to
http://localhost:8080/JSConsole/init to restore the affected files.
As a last resort or if you want to start over all the examples and exercises, you can reinitialize
all JSConsole examples by opening a browser in the URL:
http://localhost:8080/JSConsole/reset. Again, be careful because this will delete all your
c rrent progress and restore JSConsole to the initial defa
current defaults.
lts

JavaScript and HTML5: Develop Web Applications 1 - 17


JSConsole Overview

Info View Solution


Run
Revert file
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Back

File tabs
Preview and instructions
Editor e
n s
ice
b l el
fe r a
a n s
n - tr
n o
s a
JavaScript Console output a
) h i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks allows you to edit examples and exercises by focusing on the files that the
JSConsole
u
V uses. JSConsole has the following UI elements that are differentiated into sections
example
l a n
Mi based on what functions they serve
The top toolbar buttons include the following:
• Back: Goes back to the example listing; any unsaved changes are lost.
• Run: Saves all the files, and runs the example, updating the preview if available
• Info: Displays information about the current example
• View Solution: When available, displays the solved version of the current file in a pop-
up window
• Revert File: Discards all changes, and returns the file to its original state
The editor displays the contents of the current file. You can switch between files by using the
tabs on top of the editor. A pencil in the name indicates that the file is editable, whereas a lock
means that the file is read-only.
The first line in the editor indicates the path of the file being edited. You can locate the file in
the /home/oracle/demos/local folder.

JavaScript and HTML5: Develop Web Applications 1 - 18


The preview tab, when available, displays the current example preview as it would run in a
separate window. When you modify a file, if you want to see your changes in the preview,
click either of the Run buttons.
The instructions tab, when available, displays instructions for the current exercise.
The middle toolbar contains three buttons:
• Run: Saves all the files, and runs the example, updating the preview if available
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Clear Console: Clears all output from the console. This is useful before you click the
Run button to display only the current execution output.
• Run in New Window: Saves all the files, and runs the example in a new window. This
is useful to debug the example by using the browser’s
browser s tools or to see the example as it
would appear when deployed.
The console tab displays the JavaScript Console output of the example.
• Each execution is separated by a divider line.
n s e
i ce
• Errors are displayed in red and highlighted in the code.
b l el
• Each console output contains the file and the line number where the log originated.
fe ra
The files
Th fil tabt b displays
di l th
the fil
files and
d ffolders
ld as a ttree off th n s
the currentt example.
a l Y You can fifind
d th
the
actual files in the /home/oracle/demos/local folder. n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 19


Practice 1: Overview

This practice covers the following topics:


• Using NetBeans 8 to create and edit files
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Creating web applications or modifying applications to add


functionality
• Running applications inside a browser
• Debugging by using NetBeans or the browser’s tools
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 20


Assignments

• Assignments are additional practice material.


• Try to complete assignments before the next class.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Assignments can be completed at home.


• Research important documents and online material.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 21


Course Environment

Classroom Computer
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Back-End
Core Applications Resources
Services

• NetBeans 8 • Student Guide • GlassFish 4.0


• Firefox • Activity Guide Enterprise
n s e
• Chrome • Practice and Lab Application Server
lice
files • JDK 8.0 le b
• Example and demo f e ra
fil
files n s
• Interactive Quizzes n - tra
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 1 - 22


Demo: Using Your Classroom Computer

• Local computers
• Remote workstations
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Lab file location


• JSConsole tutorial

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 23


Summary

In this lesson, you reviewed the course objectives and the class
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

schedule. You met your instructor and fellow students. You also
saw an overview of the computer environment and the
JSConsole application that you will use during the course.

n s e
ice
b l el
Enjoy the next four days of er a
s f
J
JavaScript
S i t and d HTML5
HTML5: D l -itran W
Developing Web b
no n
Applications course. a
h a s eฺ
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
Vuks
an
Mil

JavaScript and HTML5: Develop Web Applications 1 - 24


Self-Study Assignment

• Install NetBeans in your home computer.


• Open a browser and go to http://www.netbeans.org.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Download and install the latest NetBeans IDE with HTML5


support.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 1 - 25


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Mil
an V u
ksa
n(
an ฺ v
mil to u
s
s
a n @
uk e thi s S t
s
)
em uden
h s
ฺrs t Gui
an
o
a deฺ
trn -
a n s fe
r
a b l el
i
ce n s e
2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Web Application Essentials ice n s e


b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
s an Day

) h a deฺ
s ฺrs t Gui Hands-On Practice

@ em uden Lecture

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 2


Objectives

After completing this lesson, you should be able to:


• Create web applications by using NetBeans
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Run HTML pages and analyze them by using the browser’s


tools
• Separate CSS and JavaScript content from HTML pages
• Run web applications by using NetBeans
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 3


Topics

• Web servers
• HTTP protocol basics
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Web applications
– Creating web applications
– Web application components:
— HTML files
— Resources n s e
ice
— Cascade Style Sheet files
b l el
— JavaScript files
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 4


Web Servers

Web applications are usually stored in web servers. They:


• Handle web requests
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Store application files


• Provide access to resources

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s server is a software that listens for requests, provides access to resources, and
• Akweb
u
V generates a response.
an •
Mil A web
eb se
server
e ca
can receive
ece e requests
equests from
o multiple
u t p e cclients,
e ts, a
and
d handles
a d es tthem
e sepa
separately.
ate y
• When a request is received, the server locates the resource, and sends its contents
back to the client. In some cases, requests are forwarded to other services that
construct the content of the response.
• Dynamic content can be generated in the server or in the client. Web applications use
dynamic content in the client with JavaScript and in the server by using an application
server.

JavaScript and HTML5: Develop Web Applications 2 - 5


Web Architecture
Clients
S
Servers

Network
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
Web server s
tr a n
o n -
s an
) h a deฺ
s ฺrs t Gui DB
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s clients connect to servers by using a network, commonly the Internet. Servers
On thekweb,
u
ancanVbe connected with one another to request information to complete requests from clients.
Mil

JavaScript and HTML5: Develop Web Applications 2 - 6


How Web Servers Work
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Process
Request

Request

Response n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks work in three stages:
Web servers
u
V A request is always initiated by the client.
l a n 1.
Mi 2.2 The server locates the resource and constructs a response
response.
3. The response with the content of the resource is sent back to the client.

JavaScript and HTML5: Develop Web Applications 2 - 7


How Web Servers Work
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Request

Response n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
When k a
s services are added, the process remains very similar.
external
u
V A client makes a request.
l a n 1.
Mi 2.2 The server tries to locate the resource and finds that it requires a third-party application
to process the request.
3. This third-party application generates communication with other resources, for example,
a database and another web server.
4. The web server constructs the response and sends it back to the client.
Enterprise Application Servers are complete servers, which contain an application engine that
can load data from external resources and a web server to handle web requests.

JavaScript and HTML5: Develop Web Applications 2 - 8


What Is a Client?

A client is an application that runs on a machine that can make


HTTP requests and interpret HTTP responses.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Web browsers
– Firefox, Chrome, Internet Explorer, and Safari
• Other applications
– Weather app on mobiles
– News readers n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n mil to u
(
In this k a
s the target client applications are web browsers.
course,
u
anV
Mil

JavaScript and HTML5: Develop Web Applications 2 - 9


HTTP Protocol

Clients communicate with the server by using the HTTP


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

protocol.
Client Server

Makes an HTTP Request

Returns an HTTP Response e


n s
ice
b l el
Makes an HTTP Request
fe r a
a n s
Returns an HTTP Response n - tr
o
s an
… ) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks is a communication protocol, which relies on TCP connections over IP to connect
• HTTP
u
V the client and the server.
an •
Mil In tthe
e HTTP pprotocol,
otoco , a
all requests
equests a
are
e independent.
depe de t
• The client might trigger additional requests but each one of these requests is completely
new to the server, and is handled independent of previous requests.
• There is no session management as part of the HTTP protocol.
• HTTP is stateless.
• Session management is accomplished by sending an identifier as part of the request
that can relate to a specific
p session.

JavaScript and HTML5: Develop Web Applications 2 - 10


HTTP Request

Request Line
Essential request information
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Method
• URI
• Version

Headers
Request options and additional client information
• Name-Value pairs n s e
ice
Message b l el
y
Body fe r a
E t information
Extra i f ti (O(Optional)
ti l) a n s
• Additional data n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks contains some information that helps the server generate a response.
A request
u
V request contains a Request Line. This contains the Uniform Resource Identifier (URI),
nEvery
a which is the name of the requested resource, and the Method used. HTTP defines the
Mil following methods: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, and CONNECT. Web
browsers use only GET or POST.
The HTTP request headers are key-value pairs that are used to provide additional
information.
• accept-encoding: Defines what encoding is expected in the response
• user-agent:
g Specifies
p the client application
pp being
g used. When you
y are usingga
browser, the name and version of the browser are supplied in this header.
• Session IDs and session information, such as cookies, can be contained in request
headers.
For more information about HTTP headers, refer to
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html.
The Message Body can contain additional information supplied by the user, such as form data
when using the POST method.

JavaScript and HTML5: Develop Web Applications 2 - 11


HTTP Request: URL
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

http://www.oracle.com/index.html If no port is
provided, the
Protocol Address Resource name default for the
protocol is used.
http://192.168.1.105:8080/res/menu.html http = 80
ftp = 21
n s e
Port
ice
b l el
fe r a
:// : n
a/ s
Protocol separator Port separator n -tr separator
Resource
o
s a n (directories)
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksshows the different components that compose a URL.
The slide
V u
i l a n
Remember that if no port is specified, the default is used. For HTTP, the default port is 80; for
M FTP, it is 21.

JavaScript and HTML5: Develop Web Applications 2 - 12


HTTP Response

Status Line
Status of the response
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Version
• Status Code
• Reason phrase

Headers
Additional response information
• Name-Value pairs n s e
ice
Message b l el
y
Body fe r a
R
Response content
t t
a n s
• Response body n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks response must contain the status line.
The HTTP
u
V codes are grouped in the following way:
l a n
Status
Mi • 1xx: Informational,
Informational for example,
example 101 Switching Protocols
• 2xx: Success, for example, 200 OK
• 3xx: Redirection. Further action is required to complete the request, for example, 301
Moved Permanently.
• 4xx: Client Error. The request contains a problem and could not be fulfilled, for example,
404 Not Found.
• 5xx: Server Error
Error. There was a problem in the server,
server for example
example, 500 Server Error
Error.
You can find the list of response codes at http://www.w3.org/Protocols/rfc2616/rfc2616-
sec10.html.
Response headers contain additional information about the response, such as the content
type, content size, user cookies, session ID, and so on.
Between the headers and the body, there needs to be an empty line.
Th body
The b d contains
t i ththe actual
t l content
t t off th
the requested
t d resource. The
Th response content
t t is
i
optional.

JavaScript and HTML5: Develop Web Applications 2 - 13


Response Bodies

A response body contains the content of a resource, including:


• Documents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Images
• Audio The client (web browser)
usually
ll knows
k h
how tto h
handle
dl
• Video or display the contents of the
• JavaScript files response.
n s e
ice
b l el
fe r a
a n s
The JavaScript code in web applications is run by the
n tr browser
-web
on the client machine. n o
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The response body contains the content of the requested resource.
u
V
i l anThe web browser displays the response content depending on the content-type that the
M server returns. Sometimes, browsers can infer from the content based on its actual structure
or how it is being used in an application.
Note that the JavaScript code is returned to the client web browser, and then executed on the
client machine. Some machines and browser configurations might block JavaScript code from
being executed.

JavaScript and HTML5: Develop Web Applications 2 - 14


Web Applications

Technical Definition
• A collection of files that are stored locally or in a web server
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

that can run on a web browser


Conceptual Definition
A application
An li ti ththatt runs on a web bbbrowser th
that:
t
• Provides the user a solution to a problem
• Is self-contained and focused n s e
lice
• Has a rich user interface
a b le
• Uses the capabilities of the user’s
user s device s f er
n a
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 2 - 15


Web Applications

JavaScript
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Resources
CSS Images
Sounds
Video

n s e
lice
HTML
Web Server Side
a b le
Application er
components
f
t r a ns
no n-
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
A web application is a collection of files stored in a directory that can be aliased by a URI.
u
V
i l anthe
Together, the files describe the user interface, and contain the application logic that runs on
M web browser. The user interface is defined by using HTML. The consistent look-and-feel
look and feel
of the interface (colors, fonts, and spacing) can be defined with CSS.
The application logic and user interactions are defined by using JavaScript.
Additional resources can be loaded to add richness to the application such as images, videos,
and sound.
Applications may have dynamic server components such as servlets, JSP, Facelets, REST
services, and so on. Server components provide dynamic data, user interfaces, styles, and so
on.
Java EE provides all the server-side technologies to create these components.

JavaScript and HTML5: Develop Web Applications 2 - 16


Web Application Structure
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Web applications are usually organized with different files and folders.
u
•V Folders separate content.
l a n
Mi • The JS files contain JavaScript code.code
• The CSS files contain layout and styles.
• The image, audio, video, and resource files add richness to applications.
• The HTML files are documents that contain the layout, information, and links to other
files.

JavaScript and HTML5: Develop Web Applications 2 - 17


Website Versus Web Application

• Similarities:
– Run on web browsers
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Have HTML5, CSS3, JavaScript, and additional resources


– Can be stored locally or on web servers
• A website
– Is a collection of information organized in pages
– Is navigation based n s e
ice
– Does not have much interactivity
b l el
• A web application
pp fe r a
a n s
– Solves one problem at a time
o n -tr
– Is interactive
s an
– Is self-contained ) h a deฺ
s ฺ r s Gui
– Is dynamic me ude nt
a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 2 - 18


The Server Side Web Application

• Generates dynamic content from data sources


• Generates dynamic pages, images, and resources
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Provides authentication, session management, and security


• Stores user and service information
• Provides XML and REST web services
• Provides AJAX and WebSocket server endpoints
n s e
ice
b l el
fe a
r DB
Client
a n s
REST
o n -tr
a n
Client
h s
a deฺ
XML
HTML 5 )
ฺrs t WS ui
s G
@ em uden
Storage Server Enterprise Server
a n S t
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Dynamic content can be generated by applications running on servers.
u
V
i l anAcontents
web application consumes the dynamic content generated by servers, and displays its
M by using separate requests that will only get the dynamic information. The layout of
the displayed content is defined and controlled by the client application.
Interactivity and dynamic content are achieved by using client-side scripting.
Another way to get dynamic content is to generate the content and layout on the server.
The server receives a request, and then generates the content as a static page that is
returned to the client so that it requires to only display the information.
Interactivity and dynamic content are achieved by using navigation and hyperlinking.
hyperlinking

JavaScript and HTML5: Develop Web Applications 2 - 19


Creating Web Applications

• Create a dedicated folder to store your application.


• Create the files for your application.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– HTML
– CSS
– JavaScript
– Images
• Organize the files in folders. n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 20


Creating HTML5 Applications in NetBeans8

In NetBeans
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

1. Select New > Project from


the menu.
2 Select the HTML5 category
2.
and the HTML5 Application
project.
n s e
3. Select a name and location ice
for your project. b l el
fe r a
4 Click Finish.
4. Finish a n s
n - tr
NetBeans creates all the o
necessary files. s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksoutlines how to create HTML5 web applications by using NetBeans 8. Follow the
The slide
u
V outlined in the slide to create a new project.
steps
l a n
Mi

JavaScript and HTML5: Develop Web Applications 2 - 21


Running the Application

NetBeans 8 runs HTML5


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

applications on an embedded web


server, and opens a web browser
window that can be used for
debugging.

n s e
ice
You can open the b l el
HTML file directly in a fe r a
browser for testing, a n s
or upload it to a web n - tr
o
server for
s an
deployment.
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s application projects can be run by using NetBeans 8. Right-click the project or an
HTML5kweb
u
V page and select Run from the shortcut menu.
HTML
l a n
Mi A browser will open with the main page or selected HTML file.
Additionally, the web applications created in this course can be run directly by opening the
HTML file in a web browser. Most browsers provide the option to open any HTML file stored in
the user’s machine.

JavaScript and HTML5: Develop Web Applications 2 - 22


Application Files
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksshows how URLs are composed when running an application in a NetBeans 8
The slide
V u
embedded web browser.
l a n
Mi Note how the project name and file name match the files in the HTML5 project.
The URL in the slide shows localhost:8383 as the server because it is running in the
embedded web browser.
If you open the index.html file directly in the browser as a file, the URL will be:
file:///home/oracle/activities/HTML5Application/index.html or something similar.

JavaScript and HTML5: Develop Web Applications 2 - 23


URL

NetBeans uses an embedded server


to run HTML5 applications.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Server Address
• Port
• Application Name*
• File Name

n s e
ice
b l el
fe r a
a n s
o n -tr
s an
) h a de*ฺ Multiple applications can
s ฺrs t Gui run on the same server.
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksshows the different components of the URL of an HTML5 web application that was
The slide
u
V by using NetBeans.
created
l a n
Mi

JavaScript and HTML5: Develop Web Applications 2 - 24


HTML Files

Hypertext Markup Language (HTML):


• It is a language used to define documents.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Structure, layout, and content


• Documents contain hyperlinks.
– To navigate to other documents
– To include resources
In a web application, HTML: n s e
ice
• Defines the page layout b l el
fe r a
• Links to other pages
a n s
• References other files n - tr
o
• Contains forms s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
HTML k a
s are the core of the web applications that are run in a browser.
files
u
V define the layout of a page, and most importantly, define the additional resources that
l a n
They
Mi need to be loaded on the page, such as style sheets, images, and scripts.

JavaScript and HTML5: Develop Web Applications 2 - 25


HTML File Structure

HTML files are text files that


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

define a document.

They contain tags


tags. Tags are
enclosed inside < >.

n s e
A tag has a Name, and might lice
have: a b le
s f er
• Attributes
Att ib t
- t r an
• Body non
s a
) h a
i d eฺ
<meta charset="UTF-8">
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
HTML files are XML-like documents. They are defined by using tags, but unlike XML, not all
u
V
tags need to be closed. However, there is an XHTML format that requires all tags to be
an
Mil closed. Some browsers allow tags with uppercase, although the standard specifies lowercase
for all tags.

JavaScript and HTML5: Develop Web Applications 2 - 26


HTML File Structure

HTML tags are closed by a


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

</ > tag that matches the


name.

What is inside the open and


close tags is the tag body.
n s e
l ice
Some tags have no body, b l e
f e raand
may not be closed.
closedanYous may
close a tag withn t r
- no body by
n o
using the
s a<TagName/>
h a deฺ
notation.
)
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 27


HTML File Structure

HTML5 files have a


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<!DOCTYPE html> directive.


The whole document is
enclosed in an HTML tag. g
An HTML document has two
sections:
n s e
• The head: Contains lice
information about theable
document s f er
- t r an
• The body: onContains the
n
h s a of the document
content
a deฺ
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
An HTML
k a
s document begins with a <!DOCTYPE html> declaration, followed by opening the
u
V root element. The entire document is contained within the <html> element.
n<html>
a An HTML document contains two mandatory sections:
Mil
• <head> contains information about the document. Everything in the head section is
loaded even before the document renders. It can contain scripts, style sheets, meta
information, and the title of the document.
• <body> contains the actual document. The elements inside the body are parsed and
loaded sequentially.

JavaScript and HTML5: Develop Web Applications 2 - 28


HTML Tag Scope
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksapplied according to their scope. A tag is considered to be active until it is closed.
Tags are
V u
i l a n
A paragraph is defined by opening and closing <p> tags. Anything inside this tag is a part of
M the same paragraph.
Some exceptions include tags that do not require a closing pair—for example, the <br> tag,
which specifies a simple new line.

JavaScript and HTML5: Develop Web Applications 2 - 29


HTML Head

Defines document properties:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Title • Viewport size


• Encoding • Styles

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Styles k a
s be defined in the head element but you may find them inside the body as well.
should
u
Va good practice to have all the styles in the head element.
l a n
It is
Mi

JavaScript and HTML5: Develop Web Applications 2 - 30


HTML Body

Contains the document content, including:


• Text
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Paragraphs
• Areas (span, div)
• Forms
• Tables
n s e
• Scripts ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 31


HTML Style (Embedded CSS)

• The contents of style tags form the Style Sheet for the
document.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• It provides font type, colors, spacing, and display information.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 32


HTML JavaScript (Embedded JS)

The contents of a script tag includes JavaScript code, which is


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

run sequentially when the tag is reached.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 33


The Application in Action
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 34


The Application in Action
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 35


CSS Files

• A CSS file contains Cascade Style Sheet definitions that can


be used inside a style tag.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• To prevent the HTML file from becoming too cluttered with


styles and to be able to reuse them, use a separate file for
CSS.
CSS

body{
font-family: Arial; n s e
background-color: #d9e7f2; e l ice
bl
margin: 0px; border: 0px; padding:ra0px;
} n s fe
h1{color: #18466a;}
n - tra
no
#nameSpan{font-weight: bold;}
a
h a s eฺ
) i d
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
You can separate the contents of any <style> tag inside a separate .css file.
u
V
an
Mil

JavaScript and HTML5: Develop Web Applications 2 - 36


JS Files

• A JS file contains JavaScript code that can be inside a script


tag.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• To prevent the HTML file from becoming too cluttered with


scripts and to be able to reuse the code, you use a separate
file for JavaScript
JavaScript.

var nameSpan = document.getElementById("nameSpan"); n s e


ice
nameSpan.innerHTML = "John";
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksseparate the contents of any <script> tag inside a separate .js file.
You can
V u
l a n
Mi

JavaScript and HTML5: Develop Web Applications 2 - 37


Resource Hyperlinking

An HTML file can reference resources to add them to the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

document.
<!DOCTYPE html>
<html>
<head>
<title>Hello Example</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
n s e
ice
el
scale=1.0">
<link href="styles/default.css" rel="stylesheet">
a b l
</head>
fe r
<body>
b d
a n s
<h1>Hello</h1>
n - tr
o
<p>Hi <span id="nameSpan">you</span>!</p>
s an
) h a deฺ
<script src="scripts/greet.js"></script>

ฺrs t Gui
</body>
</html> s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n mil to u
(
a
To linkktosother files, you use a technique called hyperlinking.
V u
an you refer files, they are added and loaded as part of the page.
When
Mil

JavaScript and HTML5: Develop Web Applications 2 - 38


Absolute Paths

• To reference a resource in another server, start the path with


the protocol.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– http://www.commonstyles.com/styles/style.css
• To reference a resource in the same server, start the path
with
ith /.
/
– /styles/style.css  http://localhost:8383/styles/style.css
n s e
Use absolute paths to: li ce
b l e
• Reference static resources in the current server sfera
• Reference static resources in a different server - t r an
n on
Do not use absolute paths for resources sinathe same application.
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
s a
To usekhyperlinking, you can refer other files by using absolute or relative paths.
u
anTheVslide demonstrates how to refer by using absolute paths.
Mil

JavaScript and HTML5: Develop Web Applications 2 - 39


Relative Paths

Relative paths are used to reference resources inside the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

same application.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 40


Relative Paths
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

styles/default.css

n s e
users/john.html ice
b l el
about.html fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
You usek a
srelative paths by locating files relative to a base file (the HTML being executed). In
u
theVexample in the slide, the base file is index.html.
l a n
Mi

JavaScript and HTML5: Develop Web Applications 2 - 41


Relative Paths
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

../scripts/greet.js

../styles/default.css

n s e
ice
b l el
../index.html fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks in the slide, the base file is /users/john.html.
In the example
u
V how to refer to a parent folder. You use ../ and you can move up folders by using
l a n
Note
Mi multiple ../../../ notations.
The slide demonstrates how to locate files in sibling folders. To understand relative paths
better, imagine how you would navigate within folders by moving up first, and then inside the
folders that you want to use.

JavaScript and HTML5: Develop Web Applications 2 - 42


Document Navigation

The anchor tab <a href=“destination”>link name</a>


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

is used to provide links to the user to navigate to a different


document.
<body>
<h2>Menu</h2>
<a href="about.html">About this Application</a><br>
<a href="users/john.html">John's page</a><br>
</body> n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Using k
the a
s anchor <a> tag, you can add navigation links to an HTML file.
u
Vanchor <a> tag is used to create hyperlinks to another document in the href attribute of
l a n
The
Mi the tag. The content displayed for the link is the content of the tag.

JavaScript and HTML5: Develop Web Applications 2 - 43


Example: Web Application

Use the JSConsole web application and run the following


example to see a sample web page composed of HTML,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

JavaScript, and CSS3.

Ti
Time Li
Limit:
it 4 minutes
i t

n s e
ice
b l el
fe r a
a n s
Try this in n - tr
o
JSConsole.
s an
) h a deฺ
ฺrs t Gui
Welcome
s
@ em uden
Welcome to the JavaScript and HTML5, develop web applications course!

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksJSConsole application and look for the example shown in the slide. You can find a
Open the
u
V example as the one shown in the slide. The application that you see gives a brief
similar
l a n
Mi introduction to the course by using HTML5 and CSS3. A sample code in JavaScript also
exists that has its output displayed on the Console tab at the bottom of the JSConsole.
Switch the file you are editing by clicking the tabs at the top of JSConsole.

JavaScript and HTML5: Develop Web Applications 2 - 44


Development Tools

• NetBeans IDE 8
• Web browser
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Web browser development tools:


– Page Inspector
– Style inspector
– Network Monitor
– JavaScript Debugger n s e
ice
– JavaScript Console
b l el
• NetBeans JavaScript
p Debugger
gg fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks is made for didactic purposes in this course, allowing you to see the important files
JSConsole
u
Vyou must edit.
that
l a n
Mi You can use any text file editor to edit HTML, CSS, and JavaScript. You can also use an
Integrated Development Environment (IDE) such as NetBeans 8 that will allow you to edit
HTML, CSS, JS, and many more files.

JavaScript and HTML5: Develop Web Applications 2 - 45


NetBeans IDE

• Integrated Development Environment:


– Organizes all your application files and settings into projects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Automates processes such as running, debugging, testing, and


profiling applications
• An
A IDE also
l provides
id many useful
f l features,
f t such
h as:
– Multiple language support
– JavaScript syntax checking and suggestions
n s e
– HTML5 structure check, tag completion, and attribute lice
suggestions a b le
s f er
– CSS syntaxt check,
h k rules
l match-up,
t h and h it ran analysis
d iinheritance l i
n - t
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ansIDE will provide many advantages and help you to improve your productivity while
Using k
V u
developing applications.
l a n
Mi

JavaScript and HTML5: Develop Web Applications 2 - 46


HTML5 Projects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Configuration
Files
Application
Fil
Files
Application
Files e
n s
Configuration
ice
Files
b l el
fer
Testing Files a
an s
n - t r
a no
h a s eฺ
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
In NetBeans 8, HTML5 projects look similar to what is shown in the slide.
u
V
i l anNote that each file in the HTML5 project is stored in a particular folder inside your hard drive.
M The Site Root is located inside the public
public_html
html folder in your project
project. You can find all your
web application files in this folder.

JavaScript and HTML5: Develop Web Applications 2 - 47


NetBeans IDE Elements
Menu Toolbar
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Project Editor
outline e
n s
ice
b l el
fe r a
a n s
Opened File
Program outputon -tr
Structure n
h s a console output)
(Server output, JavaScript
a deฺ
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksshows the different areas and sections of the NetBeans IDE. You can find more
The slide
V u
information about how to use NetBeans at https://netbeans.org/kb/index.html.
l a n
Mi

JavaScript and HTML5: Develop Web Applications 2 - 48


Running Applications
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - trWhen the
o
s an application is

) h a deฺ running,

s ฺrs t Gui additional views


are available.
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 49


Browser Development Tools
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe
Most modern browsers
r a
n s
n - tra tools to
include developer
debug
a noand analyze
h a deฺ spages.
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks browsers include some development tools that let you inspect HTML elements,
Most modern
u
V code, monitor network requests, and use many other features.
debug
l a n
Mi Unfortunately, the development tools in browsers are dependent on the browser,
environment, and version.
For example, to access the development tools:
• In Firefox, press F12 or Ctrl+Shift+I
• In Chrome, press Ctrl+Shift+J
• In Internet Explorer, press F12
• In Safari,
Safari press Command
Command-Option-I.
Option I You must,
must however,
however enable development in
settings.

JavaScript and HTML5: Develop Web Applications 2 - 50


Where Can I Learn More?

Resource Website
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

http://www.w3.org/Protocols/rfc2616/rfc2616-
HTTP Response codes
sec10.html
HTML 5 Support in
https://netbeans.org/kb/trails/php.html
NetBeans IDE Wiki
NetBeans Debugging and
https://netbeans.org/kb/docs/webclient/html5-js-
Testing JavaScript in
support.html
HTML5 Applications
n s e
Chrome developer tools ice
overview
https://developers.google.com/chrome-developer-tools/
b l el
fe r a
Firefox developer tools https://developer mozilla org/en/docs/Tools
https://developer.mozilla.org/en/docs/Tools
a n s
o n -tr
Safari developer Tools an
https://developer.apple.com/safari/tools/
s
) h a deฺ
Internet Explorer Dev
Center ฺrs t Gui
http://msdn.microsoft.com/en-US/ie/
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
ks a
u
anV
Mil

JavaScript and HTML5: Develop Web Applications 2 - 51


Summary

In this lesson, you should have learned how to:


• Create and run web applications by using NetBeans
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Separate JavaScript and CSS in different files


• Link other documents and resources
• Test and debug web applications with the browser’s tools

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 52


Practice 2: Overview

This practice covers the following topics:


• Practice 2-1: Creating HTML5 Web Applications with
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

NetBeans 8
• Practice 2-2: Separating JS and CSS Resources
• Practice 2-3: Creating a Navigational HTML5 Application

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 53


Self-Study Research Material

Create HTML5 applications by using templates.


Learn about the following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• JavaScript libraries
• CSS templates
• HTML5 page structure

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 54


Self-Study Assignment

This self-study assignment covers the following:


• Assignment 2-1: Analyze your Favorite page by using the web
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

browser tools.
– At home, by using the browser tools, analyze the request and
response of a site that you frequently access.
access
– Find the resources that are requested.
– Focus on the HTML documents, style sheets, and JavaScript
n s e
files.
e l ice
– Did you find more requests after the page loaded? r a bl
– Why
Wh d do you thi
think
k a website
b it uses suchh requests?
t a? ns
fe
– Can you see how the HTML document shapes o n -trthe page
n
layout? sa ฺ
h a de
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 2 - 55


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Mil
an V u
ksa
n(
an ฺ v
mil to u
s
s
a n @
uk e thi s S t
s
)
em uden
h s
ฺrs t Gui
an
o
a deฺ
trn -
a n s fe
r
a b l el
i
ce n s e
3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

JavaScript Fundamentals ice n s e


b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
s an Day

) h a deฺ
s ฺrs t Gui Hands-On Practice

@ em uden Lecture

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 2


Objectives

After completing this lesson, you should be able to:


• Write JavaScript code to:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Declare variables
– Create an object
– Create and call a function
– Create and iterate arrays
• Write JavaScript arrays to store data n s e
lice
• Define JavaScript objects as a key-value store
a b le
• Access the properties of an object by using get nsfe
r
a
and set n-tr no
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 3 - 3


Topics

Part I:
• The JavaScript Grammar
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Variables and Types


• Expressions and Operators
• Statements and Loops

n s e
Part II: ice
• Objects b l el
fe r a
• Arrays
A a n s
n - tr
• Functions o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 4


Comparing JavaScript and Java

JavaScript:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var x = 5;
var car = Object.create(Car.prototype);
var hello = function myFunction() {
console.log("Hello world!");
}

n s e
Java: ice
b l el
int x = 5;
fe r a
Car car = new Car(); a n s
public void myFunction() { n - tr
n o
System.out.println("Hello world!");
s a
a ฺ
} h
ฺrs) t Gu ide
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n(

u ksa (JS) is a programming language that supports scripts. This means that it is
JavaScript
V interpreted at run time rather than being compiled.
an •
Mil Itt is
s very
e y popu
popular
a in modern
ode web
eb b browsers
o se s tthat
at include
days, almost all web browsers support JavaScript.
c ude Ja
JavaScript
aSc pt interpreters.
te p ete s These
ese

• It is object-oriented. However, it does not have classes or class-oriented inheritance like


Java or C++, but it does have prototype-based inheritance. Prototyping is explained in
the lesson titled “Advanced JavaScript.”
In the slide, three basic statements are displayed: a JS variable declaration, an object
creation, and a function declaration. The same is shown for Java for comparison purposes.
Notice that variables in JSS are assigned with the var keyword and the type is not declared
(dynamic typing). Also note that functions can be assigned to a variable.
JavaScript API
The standardized version of JavaScript is ECMAScript, because Netscape delivered JS to
Ecma International for standardization. The current standard is documented in ECMA-262,
Edition 5.
Although
Al h h Ecma
E standardizes
d di JJavaScript,
S i a great many off the
h API
APIs made
d available
il bl iin
browsers have been defined at W3C.

JavaScript and HTML5: Develop Web Applications 3 - 5


Examining the Grammar of JavaScript

• JavaScript is case-sensitive:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

getElementById() ! = getElementByID()

• Escape sequence: \u Line feed


Example: n s e
ice
b l el
var x = 15; // \u000A is allowed in comments
fe r a
a n s
tr
var a = "This line wouldn't be accepted in -Java\u000A";
n on
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks 5 accepts Unicode characters in its version 3.0 or later.
ECMAScript
u
V Space
l a n
White
Mi White space characters may occur between any two tokens (a token is an indivisible lexical
unit) and at the start or end of the input. They can occur within a comment. The ECMAScript
white space characters that are allowed are tab (\u0009), vertical tab (\u000B), form feed
(\u000C), space (\u0020), no-break space (\u00A0), the byte-order mark (\uFEFF), and
any other Unicode space separator. JavaScript ignores the spaces that appear between
tokens.
Line Terminators
Line terminators affect the process of automatic semicolon insertion in JavaScript. A line
terminator cannot occur within any token, except a string literal (for example, “This is a string
literal”).
Escape Sequence
The Unicode escape sequence in JavaScript consists of six characters, starting with \u, plus
four hexadecimal digits. If a Unicode sequence occurs in a comment, it is never interpreted
and it is only part of the comment. The same happens within a string literal.

JavaScript and HTML5: Develop Web Applications 3 - 6


Examining the Grammar of JavaScript

• Comments:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

// This is a single-line comment, until the end of line


/* And here is a multi-line
comment, notice that this
type of comments cannot be nested */

• Literals: n s e
ice
null
b l el
"True"
fe r a
'true' a n s
true n - tr
o
15.5
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks
Comments a
V u
i l a n
Comments can be single or multiline. The code in the slide shows an example for each one.
M Literals
Literals represent values in JavaScript. There are null, boolean, numeric, string, or regular
expression literals.

JavaScript and HTML5: Develop Web Applications 3 - 7


Examining the Grammar of JavaScript

Automatic Semicolon Insertion


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var x = 15.5
var y = "Total";

semicolon is
inserted s e
ce n
el i
a = b + c
a b l
fe r
(d + e) = f;
a n s
o n -tr
semicolon
a n is NOT
h a s eฺ
inserted
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
Semicolonsa
s may be omitted because they are automatically inserted into the source code,
u
V in do-while, continue, break, return, and throw statements. The code in the
except
l a n
Mi slide shows some examples of how semicolon is inserted in some situations.
Line break plays an important role in the rules of automatic semicolon insertion. If there is a
line break between two statements and the first statement does not have a semicolon, it is
automatically inserted. However, this rule is leveraged with the ability of the parser. If the
parser is unable to parse the token stream, a semicolon is automatically inserted; if it can
parse the token stream, the parser does not insert the semicolon. An example is shown in the
second code in the slide, where a semicolon is not inserted at the end of the first line due to
the parenthesis at the beginning of the second line
line, which tells the parser that the c at the end
of the first line could be a function.
Despite the automatic semicolon insertion, it is recommended that you provide an explicit
semicolon in cases where the provided code might confuse the parser.

JavaScript and HTML5: Develop Web Applications 3 - 8


Examining the Grammar of JavaScript

• Identifiers
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

this_is_a_variable_name
_another_variable_name
$ thi d
$a_third_variable_name
i bl

• Reserved Words n s e
ice
break do instanceof typeof case
b l el
else new var catch fe
finally r a
a n s
return void continue for
n - tr switch
while debugger function this a n
o with
h a s eฺ
default if throw
ฺ r s ) delete
u id in
try e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Identifiers
u
•V Any name given to a variable or function that is not a reserved word is an identifier.
l a n
Mi • The dollar symbol ($) and the underscore ((_)) character are permitted anywhere in an
identifier.
• The code in the slide shows examples of identifiers in JavaScript.
Reserved Words
JavaScript reserves some words that cannot be used as identifiers, as shown in the table in
the slide. There are also some future reserved words that are being used in extensions of the
language, and therefore, cannot be used as identifiers either. These words are enum,
extends, super, const, export, and import. And if JavaScript is in strict mode, more
reserved words are added: implements, let, private, public, yield, interface,
package, protected, and static.

JavaScript and HTML5: Develop Web Applications 3 - 9


Examining the Grammar of JavaScript

• Example with strict mode:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function findPrice() {
'use strict';
price
i = 1200;
1200 // thi
this li
line causes an uncaught
ht
// ReferenceError
}
n s e
ice
• Non-strict mode or normal JavaScript:
b l el
fe r a
a n s
function findPrice() {
n - tr
price = 1200; o
// this line does notncause an error
} sa ฺ h a de
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Strict Mode
u
V invoke strict mode by using the "use strict"; sentence at the beginning of a file or a
l a n
You
Mi function. Strict mode is secure, robust, and error-free
error free compared to normal JavaScript.
For example, in strict mode, all variables must be declared. The first code in the slide shows
an example of strict mode in a function and the second code shows a non-strict mode. When
you call the findPrice function, the first code will throw a ReferenceError and the
second code will not. To debug the error, you should declare the variable: var price =
1200.

JavaScript and HTML5: Develop Web Applications 3 - 10


Topics

Part I:
• The JavaScript Grammar
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Variables and Types


• Expressions and Operators
• Statements and Loops

n s e
Part II: ce
el i
• Objects a b l
fe r
• Arrays a n s
n - tr
• Functions o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 11


Types

Type Example
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Undefined var a = undefined;


Null var b = null;;
Boolean var d = true;
String var c = "This is a string"; n s e
ice
Number var n = 15.5; b l el
fe r a
Object a n s
var o =
n - tr
o
Object.create(Object.prototype);
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
an(
ks
In JavaScript, there are six types of values. These types are shown in the table in the slide. A
u
V
value always has an associated type.
an
Mil • The Undefined and Null types
respectively.
yp have one value each: undefined and null,,

• The Boolean type represents two possible values: true and false.
• The String type represents values enclosed in single quotation marks or double
quotation marks, similar to what is shown in the example in the slide.
• The Number type represents the double-precision 64-bit format values. Number is
equivalent to the Double type in Java.
• The Object type is composed of properties, where a property has a name and a value.
JavaScript variables are untyped. You can assign a value of any type to a variable. That is
why all the variables in the examples in this slide are declared with the var keyword.

JavaScript and HTML5: Develop Web Applications 3 - 12


Declaring a Variable

• Variable declaration:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var a;
var x = 15.5;
var y = "Total";
Total ;

• Variable in a function: n s e
lice
function declareVariable() {
a b le
if (true) {
s f er
var x = "Declared
l d i
in a bl
blockk off code";
d
- t r an
}
console.log("Value of x: " + x); a n
on
}; h a s eฺ
d
declareVariable(); ฺrs) Gui
e ms dent
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
Variables a
s are where values are stored. If a variable is declared without assigning a value to it,
itsV u
type is undefined. Any variable that is declared in JavaScript without the var keyword is
l a n
Mi created in the global scope.
Scopes
A variable in the global scope is declared outside of a function definition, and persists through
the life of the program. Also, the global variable can be accessed and altered by any function.
A significant difference with Java and other languages with regard to the scope of a variable is
that in JavaScript, there is no block scope. This means that if a variable is declared in a block
of code, like a for or at any position inside a function, the variable would still be visible within
the function in which it is declared. This is called function scope.
An example of function scope is shown in the second code in the slide, where the variable x
is declared in the if block, but it is still visible in the function.
Hoisting
In JavaScript, you can refer to a variable that is declared later in the code, without getting an
exception. This is known as hoisting.
However, it is recommended that variables should always be declared at the top of the
function.

JavaScript and HTML5: Develop Web Applications 3 - 13


Example: Variables and Types

Use the JSConsole web application and run the following


example to see how a declared variable has a function scope.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
f er a
T
Try this
thi s
an section
ti
n - t r
inoJSConsole.
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksthe output of the code on the Console tab.
Observe
u
Vcode in JSConsole is the same as in the slides. You can refer to the slides at any time,
l a n
The
Mi while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 3 - 14


Topics

Part I:
• The JavaScript Grammar
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Variables and Types


• Expressions and Operators
• Statements and Loops

n s e
Part II: ce
el i
• Objects a b l
fe r
• Arrays a n s
n - tr
• Functions o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 15


Creating an Array and an Object

• Initializers:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var courses = ["Java","JavaScript","Web Services"];


var students = [12,5,7];

var course = {name: "JavaScript", students: 5,


frequency: "daily"};
n s e
ice
• Creating an array with new:
b l el
fe r a
var students_new = new Array();
y
a n s
o n -tr var students_new_init = new Array(12,5,7);

• Creating an object with new: s an


) h a deฺ
var courses_new = new Courses();
s ฺ rs t Gui
var courses_new_init = newmCourses(12,5,7);
@ e uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
Examplesk a
s for the simplest expressions in JavaScript are: this; (the this keyword), true;
(a V u
literal value), or x; (a variable).
l a n
Mi The basic expressions also include initialization of Object and Array objects. Initialization
occurs when an expression creates a new array or object.
An initialized array is enclosed in square brackets and it contains expressions or other arrays.
An initialized object is declared by using pairs of property names and values. Another object
can be supplied as a value. An object can be also initialized with empty properties: var
course = {};.
Both types of array and object initialization are shown in the first and second code examples
in the slide.
The new Operator
You can create a new object or array by initializing it as shown in the slide. Another option is
to use the new operator, as shown in the last two codes in the slide. The new operator creates
a new object and invokes the constructor to initialize the properties.
It is recommended that new objects or arrays be created by using initialization.

JavaScript and HTML5: Develop Web Applications 3 - 16


Accessing an Array and an Object

var myObject = {
name: "Ring",
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

diameter: 12,
specs: {
material: "Wood",
waterProof: false
}
};
var myArray = ["one", "two", 3, "four", 5];

• By using the dot notation (only for objects): n s e


ice
myObject.diameter; 12
b l el
myObject.specs.waterProof; false
fe r a
a n s
n - • By using the bracket notation: tr
o
myObject["diameter"]; 12
s an
myObject["specs"]["material"];
) h a deฺ
"Wood"

myArray[0]; "one" s ฺrs t Gui


myArray[5]; undefined em d en
a n @ S t u
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
There kare a
s two ways to access the properties of an object or array:
u
V By using the dot notation: Expression.IdentifierName
1.
l a n
Mi 2.2 By using the bracket notation: Expression [Expression]
Both examples are shown in the slide. Note that the access to properties can be chained
together.

JavaScript and HTML5: Develop Web Applications 3 - 17


Creating and Calling a Function

• Function definition:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function multiply(x, y) {
var result = x * y;
return result;
}

n s e
ice
• Function invocation:
b l el
fe r a
a n s
o n -tr
var total = multiply(135,6);
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks a function, use the function keyword, followed by zero or more parameter names,
To define
u
nandVthen the function body, which is the JavaScript code between the curly braces. The first
a code in the slide shows this.
Mil If the function does not return a value, JavaScript returns undefined.
To call a function, write the name of the function, an open parenthesis, the list of parameters,
and then add a closing parenthesis at the end.

JavaScript and HTML5: Develop Web Applications 3 - 18


Working with Operators

Arithmetic Relational Logical Assignment Special


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

++ == && = ,

-- != || delete
Bitwise
+ === ! & in

- !==
Conditional
| instanceof
n s e
ice
* > ?: ~ void
b l el
fe r a
/ >= ^
a n s typeof

n - tr
% < >> n o
s a
<= ) h a
i d eฺ
s ฺrs t Gu <<

@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
The table a
s in the slide shows the different operators in JavaScript. They can be categorized
u
V Arithmetic (++, --, +, -, *, /, %), relational (==, !=, ===, !==, >, >=,
into:
l a n
Mi <, <=), logical (&&, ||, !), assignment (=), bitwise (&, |, ~, ^, >>, <<), conditional
(? :) and special operators (, , delete, in, instanceof, void, typeof). In the
following slides, examples of usage of the different operators are provided.

JavaScript and HTML5: Develop Web Applications 3 - 19


Operators

• Arithmetic operators:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

9 – 5; 4
[9] * ['5']; 45
"9" + 5; A String
g :"95"

• Relational operators:
n s e
true
ice
el
9 == '9';
9 === '9'; false
a b l
fe r
a n s
• Logical operators:
o n -tr
s a n"another"
var a = "string" && "another";
var o = "string" || "another";s) h i eฺ
a d"string"
s r t Gu
ฺfalse
var n = !"string";
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks there are binary operators that combine two expressions or operands, and
In JavaScript,
u
V operators, which are part of a single expression and include only one operand.
nunary
a Arithmetic Operators
Mil
JavaScript tries to convert the type of operands according to the operator used. An example is
shown in the first code in the slide, where [9]*['5'] produces the number 45 as the result.
The + operator is used not only to sum, but also to concatenate strings.
Relational Operators
Relational or comparison operators (==, !=, ===, !==, >, >=, <, <=), return a
logical value based on whether the comparison between the operands is true or false
false.
The difference between the operators == and === is that == is equal and === is strict equal,
which means that it returns true if the operands are equal and of the same type.
Logical Operators
Logical operators (&&, ||, !) work with Boolean values and return a Boolean value.
However, if they are used with non-Boolean values, they may return a non-Boolean value.
Examples are shown in the slide
slide.

JavaScript and HTML5: Develop Web Applications 3 - 20


Operators

• Assignment operator:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

a = b;
x += 1;

• Bitwise:
4 n s e
ice
el
5 & 6; // 101 & 110 = 100
a b l
fe r
a n s
o n -tr • Conditional operator:
condition ? expression_1 : expression_2 s an
) h a deฺ
var status = (age >= 18)? "major" s ui
ฺrs t:G"minor";
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks Operator
Assignment
u
Vassignment operator (=) is used to assign a value (right operand) to a value or property
l a n
The
Mi (left operand).
In addition to normal assignment (=), this operator can be combined with other operators,
which is called a shortcut. For example, a += b is equivalent to a = a + b.
In the code in the slide, x += 1 is recommended over x++, for readability.
Bitwise Operator
Bitwise operators (&, |, ~, ^, >>, <<) work with their operands as zeros and ones in
sequence of 32 bits
bits, instead of decimal
decimal, hexadecimal
hexadecimal, or octal numbers
numbers. However
However, they return
the result as numbers.
Conditional Operator
The conditional operator (? :) is the only operator in JavaScript with three operands (ternary
operator). As indicated in the third code snippet in the slide, based on a condition (before the
?), the operator can evaluate one expression if true [before the colon (:) , expression_1
in the slide]] or another if false [[after the colon ((:),
), expression
p ]
_2].

JavaScript and HTML5: Develop Web Applications 3 - 21


Special Operators

• Comma operator:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

for (var i = 0, j = 9; i <= 9; i++, j--)


console.log(i + " , " + j);

• delete operator:
var i = { a : 5, s : "String", b : 15 }; n s e
returns true. i = {a : 5, b : 15} ice
delete i.s;
true b l el
"b" in i;
false fe r a
"s"
s in i;;
a n s
on -tr
var i = [ 5, "String", 15 ];
a n
delete i[1]; returns true. i = [5,s undefined
ฺ , 15]
true h a e
0 in i;
ฺ r s ) u id
1 in i; false s
em uden tG
a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The comma operator is primarily used in the for loop to handle multiple loop variables, as
u
V
shown in the example in the slide. This binary operator evaluates both left and right operands
an
Mil but returns only the value of the right operand.
The delete operator removes an object, an object property, or an array element. The
operator returns true if it could delete the property or element; otherwise, it returns false.
You cannot delete variables that are declared explicitly with var.
If an array element is deleted, the length of the array is not affected, because the element
value is replaced with undefined, as shown in the last code in the slide. Notice the use of
the in operator to check if a property is in an object. The in operator evaluates only for
properties
ti iin an object,
bj t nott values.
l

JavaScript and HTML5: Develop Web Applications 3 - 22


Special Operators

• void operator:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<a href="javascript:void(0);">This link does nothing</a>


<a href="javascript:void(aMethod());">This link calls
aMethod</a>

• typeof operator: n s e
ice
var a = [1, 2, 3, 4]; b l el
fe r a
a n s
typeof undefined; "undefined"
o n -tr
typeof "Hello"; "string" a n
typeof a; "object" h s
a deฺ
"number" sฺrs
) i
typeof a[0];
m dent Gu
e
@ Stu
a n
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
The void
k a
s operator evaluates an expression, and returns undefined. Its syntax is void
V u
expression or void(expression). The most frequent usage of this operator is with
l a n
Mi JavaScript URIs (javascript: URL), to evaluate the expression, but without replacing the
content of the web page with the returned value, as shown in the first code in the slide.
typeof is a unary operator that returns a string with the type of its operand. Some examples
are shown in the slide.

JavaScript and HTML5: Develop Web Applications 3 - 23


Example: Expressions and Operators

Use the JSConsole web application and run the following


example to see how to create and access arrays and objects,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

create and call a function, and work with operators.

Ti
Time Li
Limit:
it 10 minutes
i t

n s e
ice
b l el
f er a
T
Try this
thi s
an section
ti
n - t r
inoJSConsole.
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksthe output of the code on the Console tab.
Observe
u
Vcode in JSConsole is the same as in the slides. You can refer to the slides at any time
l a n
The
Mi while reviewing the code in JSConsole.
Do not forget to review the void operator in the index.html file and the output on the
Preview tab.

JavaScript and HTML5: Develop Web Applications 3 - 24


Topics

Part I:
• The JavaScript Grammar
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Variables and Types


• Expressions and Operators
• Statements and Loops

n s e
Part II: ce
el i
• Objects a b l
fe r
• Arrays a n s
n - tr
• Functions o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 25


Writing Statements

• A block of code:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

{
<statement 1>
...
<statement n>
}

• Declaring a variable: n s e
ice
var x = 15; b l el
fe r a
a n s
o n -tr • Conditional:
if (expression) { s an
) h a deฺ
<statement 1>
} [else { <statement 2> }] sฺr
s Gui
e m dent
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks are commands to be executed by the browser. Statements are executed in order,
Statements
u
V top to bottom. Multiple statements can be in a single line if they are separated by a
from
l a n
Mi semicolon (;).
A block of code is a group of statements delimited by curly braces, as shown in the slide. A
block of code does not end with a semicolon. Also remember that a block of code does not
have a scope and the variables that are declared in a block are not exclusive of the block.
They are visible in the function in which they are declared.
var Statement
With var, the variable is defined and initialized.
Empty Statement
An empty statement is declared with only a semicolon (;) and it does nothing.
if Statement
A conditional with the if statement executes a statement based on whether an expression is
true or false. If the expression is true, the block of code is executed; otherwise, the block of
code under the else statement ((if p provided)) is executed.

JavaScript and HTML5: Develop Web Applications 3 - 26


Writing Statements

• switch and break:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

switch (expression) {
case label_1:
<statements 1>
[break;]
case label_2:
<statements 2> n s e
ice
el
[break;]
... a b l
fe r
default:
a n s
<statements n>
n - tr
o
an
[break;]
}
h s
a deฺ
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks statement evaluates an expression, and based on the case label that matches
The switch
u
theVexpression, it executes the block of code that is associated with the case label. If there is
l a n
Mi no match, the optional default statements are executed. After a match is found and the flow has entered into a case label, the optional break statement can be used to exit from a switch.
The types of values allowed in the case label are numbers or strings.

JavaScript and HTML5: Develop Web Applications 3 - 27


Writing Statements

• return:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function multiply(x, y) {
var result = x * y;
return result;
l
}

n s e
ice
• with:
b l el
fe r a
a n s
with (object) {
o n -tr object>
n
<statements calling the properties of the
} sa h a deฺ
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
return k a
sspecifies the value to be returned by a function. It can also cause early return from a
u
V An example of return is shown in the slide.
function.
l a n
Mi The with statement adds the members of an object to the current scope. However, with is forbidden in strict mode. It throws a SyntaxError if it is used in strict mode. The use of the
with statement is not recommended.

JavaScript and HTML5: Develop Web Applications 3 - 28


Writing Statements

• try and throw:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function myFunction() {
try {
functionCanThrowAnException();
if (condition) {
throw "myException";
}
n s e
}
lice
catch (e){
a b le
logError(e);
s f er
}
- t r an
finally {
n on
closeFiles();
s a
}
) h a
i d eฺ
} sฺrs Gu
m dent
e
@ Stu
a n
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
The tryk a
sstatement marks a block of statements where an exceptional condition can occur.
u
V exceptional condition can be specified with a throw statement.
This
l a n
Mi The throw statement throws an exception and if throw is in a try block, control goes to the catch clause. Otherwise, control goes to the catch clause of the try in the calling function.
The final block of statements is always executed after the try and catch statements, no
matter what the flow was. The try…catch statements can be nested.

JavaScript and HTML5: Develop Web Applications 3 - 29


Statements

• Labeled statement:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

myLabel:
<statement>

• debugger:
function iNeedToStopHere(){
debugger;
n s e
ce
// do debugging stuff
} el i
a b l
• Continue: fe r
a n s
n - tr
for (var i=0; i<10; i++) { o
if (i === 5) continue;
s an
h
console.log("This number is:"
) a+ i);
i d eฺ
} sฺrs Gu
m dent
e
@ Stu
a n
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k a
s any statement can be labeled. Labeled statements are used only in conjunction
In JavaScript,
u
nwithV break and continue statements, which means that labels are mostly used inside loops
a or conditionals. A label can be any identifier that is not a reserved word.
Mil The debugger statement is like a breakpoint in the source code. When it is inserted, it calls
any debugging functionality, if there is one available.
The continue statement terminates the execution of statements in the current loop, and
restarts the execution of the next loop. The example in the slide prints all the numbers, except
the number five.
The identity or strict operator (===) that is used in the third code in the slide checks the value
and type of operators. It results in a true value only if both operator types are the same. Use
this operator if you need type comparison also; otherwise, you can use the equal operator ==
that converts the operands if they are not of the same type.

JavaScript and HTML5: Develop Web Applications 3 - 30


while Loop

• while:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var i = 0;
while (i < 10) {
console.log(i+=1);
}

n s e
ice
• do/while:
b l el
fe r a
var i = 0;
a n s
do {
n - tr
semicolon o
an
console.log(i+=1);
} while (i < 10);
h s
a deฺ
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
The while
k a
s loop executes a block statement if the expression in parentheses evaluates to
u
V While the expression is true, the block statement is executed. When the expression in
true.
l a n
Mi parentheses is false, it does not execute the statement in the block of code any more, and
continues with the logic of the program. An example is shown in the slide, where the while
loop prints the numbers from one to ten.
The do/while loop is a very similar control structure to the while loop, except that it
executes the block statement at least once, because it evaluates the expression in
parentheses at the end of the body of the loop. The example in the slide prints the numbers
from one to ten.

JavaScript and HTML5: Develop Web Applications 3 - 31


for Loop

• for:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

for (var i = 1; i <= 10; i+=1){


console.log(i);
}

• for/in:
var myObject = {
n s e
one: "value of property one", ice
two: "value of property two" b l el
} fe r a
a n s
for (var myVar in myObject) {
n - tr
if (myObject.hasOwnProperty(myVar)) n {o
console.log(myVar); a
s eฺ
h a
}
ฺ r s ) u id
} s tG
em uden
a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The for loop includes the counter in the parentheses. The expression on the left initializes
u
V
the loop, the expression in the middle (after the first semicolon) checks whether the loop must
an
Mil still continue (if the condition is false, the loop breaks), and the expression on the right
updates the counter before the next loop starts. The example in the slide prints the numbers
from one to ten.
The for/in loop iterates the property names of an object. It iterates only through
enumerable properties (properties with a flag stating that they can be iterated). The example
in the slide prints “one” and “two” in the console. Notice in the example the call to the
hasOwnProperty method to make sure that the property is from the object and not from the
prototype chain.
chain

JavaScript and HTML5: Develop Web Applications 3 - 32


Example: Statements and Loops

Use the JSConsole web application and run the following


example to see the different loops.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 5 minutes


End of Part I

n s e
ice
b l el
fe r a
a n s
Try this section n - tr
o
in JSConsole.
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksthe output of the code on the Console tab.
Observe
u
Vcode in JSConsole is the same as in the slides. You can refer to the slides at any time
l a n
The
Mi while reviewing the code in JSConsole.
This is the end of Part I. You can take a break before we move to Part II.

JavaScript and HTML5: Develop Web Applications 3 - 33


Topics

Part I:
• The JavaScript Grammar
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Variables and Types


• Expressions and Operators
• Statements and Loops

n s e
Part II: ce
el i
• Objects a b l
fe r
• Arrays a n s
n - tr
• Functions o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 34


Creating Objects

• Creating an empty object:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var obj_1 = {};


var obj_2 = new Object();
var obj
j_3 = Object.create(null);
j

• Creating an object:
var person = { n s e
"full-name" : "John Doe", lice
a b le
er
age: 35,
s f
an
address: {
r
address_line1: "Clear Trace, Glaslyn,-tArkansas",
"postal code": "76588-89" n on
s a
}
) h a
i d eฺ
}; s s u
ฺr t G
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
In JavaScript, everything that is not a primitive type (number, string, boolean, null, undefined)
u
V
is an object. In an object, you can store multiple properties in the form of name-value. It can
an
Mil also store other objects or functions. Objects are passed by reference.
You can create an empty object by initializing it with curly braces (= {}), by using the new
keyword, or by using Object.create, as shown in the first code in the slide.
As shown in the second code in the slide, the names of properties in an object can have
quotation marks. Quotation marks are mandatory for those property names that include a non-
valid JavaScript identifier ("full-name" and "postal code" in the example).

JavaScript and HTML5: Develop Web Applications 3 - 35


Creating Objects

• Creating an object with new:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function Tree(type, height, age) {


this.type = type;
this.height = height;
this.age = age;
}
n s e
ice
var mapleTree = new Tree("Big Leaf Maple", 80, 50);
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n mil to u
(
A second a
ks alternative to creating an object is to use a constructor function. The convention is
u
nto V
differentiate a constructor function from a normal function by using a capital initial letter (“T”
a in “Tree”). As shown in the slide, the constructor function receives parameters and uses the
Mil this keyword to initialize the object’s properties with the values passed.
After defining the object type, you use the new keyword to create an object, as shown in the
slide. After creating the mapleTree object, three properties are now initialized with the values
passed.

JavaScript and HTML5: Develop Web Applications 3 - 36


Creating Objects

• Creating an object with prototypes (syntax):


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var obj = Object.create(Object.prototype [,properties]);

• Examples:

var myChild = Object.create(Object.prototype); //Object {}


myChild = Object.create({a:10, b:30}); // Object {a=10, b=30} n s e
ice
var myObj = { b l el
a : 10, fe r a
a n s
};
b : 30
n - tr
o
myChild = Object.create(myObj);
s an
myChild.a; //10
) h a deฺ
myChild.b; //30
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks in the slide shows how to create an object with prototypes. Every object is linked to
The code
u
V object called a prototype. From the prototype, objects can inherit properties. If a
another
l a n
Mi property is retrieved in an object, JavaScript will try to find it in the object first, and if it cannot
find it, JavaScript will try to find it in the object’s prototype.

JavaScript and HTML5: Develop Web Applications 3 - 37


Accessing Object Properties
var myObject = {
name: "luggage",
length: 75,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

specs: {
material: "leather",
waterProof: true
}
}

• Getting and setting properties:


myObject["name"]; // "luggage"
myObject.name; // "luggage" n s e
ice
myObject.specs.material; // "leather"
b l el
myObject["specs"]["material"]; // "leather"
fe r a
myObject.width; // undefined
a n s
-tr
myObject.tags.number; // TypeError thrown
o n
myObject["name"] = "suitcase"; a n: "suitcase"
// name
s
myObject.name = "suitcase";
) h
//anamed:eฺ"suitcase"
myObject.width = 40;
s ฺ rs //t G ui a new property
creates
myObject.tags.number = 6;
e m den// TypeError thrown
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
Because a
ksan object is a container of properties, there should be ways to get and set properties
onV u
the object. There are two ways to access the properties of an object: by using the dot
l a n
Mi notation or by using the bracket notation. Both examples are shown in the slide. Note that the
access to properties can be chained together.
When a property that does not exist in the object is set to a value, the property is added to the
object.
Properties in Prototypes
If a property is queried in an object, and if it does not exist in the object, JavaScript tries to
retrieve it from the prototype object.
Property Attributes
Some properties are read-only. This is possible due to the property attributes that every object
has: value, writable, enumerable, and configurable.
• value is the property’s value.
• If writable is set to false, an attempt to change the value of the property will not
succeed.
• If enumerable is true, the property is enumerated by a for-in enumeration.
• If configurable is set to false, an attempt to delete or change the property’s
attributes will not succeed.
JavaScript and HTML5: Develop Web Applications 3 - 38
Working with Object Properties

• Deleting properties:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

delete myObject.length; true, even though it doesn't


delete myObject.height; exist in the object

• Testing and enumerating properties:


var myObject = {
one: "property value one",
n s e
two: "property value two" ice
} b l el
fe r a
a n s
for (var myVar in myObject) {
o n -tr
if (myObject.hasOwnProperty(myVar)) n {
console.log(myVar); a
s eฺ
h a
}
ฺ r s ) u id
} ms e ude tG n
a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Object Attributes
u
V
i l anObjects have object attributes: prototype, class, and extensible.
M Deleting Properties
The delete operator removes a property from an object. However, delete does not remove
properties that have their configurable attribute set to false.
hasOwnProperty Method and Looping Through Properties
As seen in the section where the for/in loop was explained, the hasOwnProperty method
can be used to query if a property is from the object and not from the prototype chain. The
for/in loop enumerates the property names of an objectobject. The example in the slide prints
“one” and “two” in the console.

JavaScript and HTML5: Develop Web Applications 3 - 39


Accessing Object Properties

• Property get and set:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var obj = {
a : 45,
get double_a()
double a() {return this.a * 2},
set modify_a(x) {this.a -= x;}
};
n s e
ice
obj.a; // 45
b l el
obj.double_a; // 90
fe r a
obj.modify_a
bj dif = 40;
40
a n s
obj.a; // 5 n - tr
o
obj.double_a; // 10
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k a
s allows access to properties without requiring the use of explicit method calls, It
JavaScript
u
V this possible with the get and set keywords. JavaScript invokes these functions as
makes
l a n
Mi methods of the object on which they are defined. An example is shown in the slide.
In the example, the function double_a is called when the property obj.double_a is looked
up. And the modify_a function is called when there is an attempt to set the obj.modify_a
property.

JavaScript and HTML5: Develop Web Applications 3 - 40


Object Methods

• Object method example:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var myObj = {
print: function() {
console.log("Hello World!");
}
};

n s e
myObj.print();
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Objectsk a
scan have methods, they are functions as a property of an object. The example in the
u
V shows an object called myObj with a print method. When the method
slide
l a n
Mi myObj.print() is called the “Hello World!” message is printed in the console.

JavaScript and HTML5: Develop Web Applications 3 - 41


Example: Objects

Use the JSConsole web application and run the following


example to see how to create objects, access object properties,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

and call object methods.

Ti
Time Li
Limit:
it 15 minutes
i t

n s e
ice
b l el
f er a
T this
Try thi s
an section
ti
n - t r
inoJSConsole.
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksthe output of the code on the Console tab.
Observe
u
V Run this example in Firefox to be able to execute the .toSource() method
l a n
Note:
Mi successfully.
The code in JSConsole is the same as in the slides. You can refer to the slides at any time
while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 3 - 42


Topics

Part I:
• The JavaScript Grammar
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Variables and Types


• Expressions and Operators
• Statements and Loops

n s e
Part II: ce
el i
• Objects a b l
fe r
• Arrays a n s
n - tr
• Functions o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 43


Creating Arrays

• Initializing an array:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var myNewEmptyArray = [];

var numbers
b = [1
[1, 2
2, 3
3, 4
4, 'fi
'five'];
']

• Creating an array with new: n s e


ice
var myNewEmptyArray = new Array(); b l el
fe r a
a n s
var myNewNonEmptyArray = new Array(15);
o n -tr
var numbers = new Array(1, 2, 3, 4, s'five'); an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
An array a
ksis a collection or list of values, with methods to run against the collection.
V u
nInitialization occurs when the expression creates a new array by using square brackets that
a surround zero or more values separated by commas, as shown in the first code in the slide.
Mil
An array in JavaScript can contain any combination of values. Also, it can contain other
arrays.
The new Operator
Another option to create an array is to use the new operator, as shown in the second code in
the slide. The three ways of using the Array() constructor are as follows:
g the constructor with no arguments.
1. Calling g In this case,, an empty
p y arrayy is created.
2. Calling the constructor with a single argument, which is the length of the array
3. Sending the elements of the array as constructor arguments
It is recommended that arrays be created by using initialization, as shown in the first code in
the slide.

JavaScript and HTML5: Develop Web Applications 3 - 44


Accessing Array Elements

• Length of an array:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var c = ["blue","red","green","purple"];
c.length; 4
c[20] = "white";
c.length;
l th 21

• Iterating arrays: e
n s
ice
el
for (var i = 0; i < c.length; i += 1)
{ a b l
fe r
console.log(c[i]);
g( [ ]);
a n s
o n -tr }
for (var i in c) a n
{ h s
a deฺ
console.log(c[i]); )
ฺrs t Gui
s
}
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
Length a
ksof an Array
u
Vlength property of an array represents the number of elements in an array. An example
l a n
The
Mi of the syntax is shown in the first code in the slide. The length of the array is one more than
the highest index. The index of the first element in an array is 0.
The length property is not necessarily the number of values in the array. If a value is
assigned an index that is greater than the current length, the length property is set to the
index + 1, as shown in the example.
Iterating Arrays
Too iterate
te ate arrays,
a ays, tthe
e for
o aand
d for/in
o / loops
oops cacan be used, as sshown
o in tthe
eeexamples
a p es in tthe
e
slide. The examples print the array elements in the console.
Note that for/in also loops over new properties that are added to the prototype chain, and
that the order is not guaranteed. Therefore, the for/in loop is not recommended to iterate
arrays.

JavaScript and HTML5: Develop Web Applications 3 - 45


Multidimensional Arrays

• Creating multidimensional arrays:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var myArr = new Array(10);


for (i = 0; i < 10; i++) {
myArr[i]
y [ ] = new Array(10);
y( );
for (j = 0; j < 10; j++) {
myArr[i][j] = "[" + i + j + "]";
}
n s e
}
ice
b l el
fe r a
var tic
tic_tac_toe
tac toe = [
a n s
[ 0, 0,'X'],
n - tr
o
['X',0,'X'],
s an
['X',0, 0]
) h a deฺ
];
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks in an array may be of any type. The elements in an array can be other arrays as
The elements
u
V Multidimensional arrays are built in JavaScript by nesting arrays. The first code in the
well.
l a n
Mi slide shows an example of how to create a two-dimensional array with two for loops.
The second code in the slide shows an example of how to create a two-dimensional array but
during the initialization of the array.

JavaScript and HTML5: Develop Web Applications 3 - 46


Example: Arrays

Use the JSConsole web application and run the following


example to see how to work with arrays.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 10 minutes

n s e
ice
b l el
f er a
T this
Try thi s
an section
ti
n - t r
inoJSConsole.
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksthe output of the code on the Console tab.
Observe
u
Vcode in JSConsole is the same as in the slides. You can refer to the slides at any time
l a n
The
Mi while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 3 - 47


Topics

Part I:
• The JavaScript Grammar
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Variables and Types


• Expressions and Operators
• Statements and Loops

n s e
Part II: ce
el i
• Objects a b l
fe r
• Arrays a n s
n - tr
• Functions o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 48


Defining Functions

• Function definition: Name of the function


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Arguments

function multiply(x, y) {
var result = x * y;
return result; b d
body
}
n s e
ice
• Calling a function:
b l el
fe r a
var total
l = multiply(135,6);
l i l ( ) a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks function is used to define a function, followed by zero or more parameter
The keyword
u
V Immediately after this comes the function body, which is the JavaScript code between
names.
l a n
Mi the curly braces. An example is shown in the first code in the slide.
If the function does not return a value, JavaScript returns undefined.
To call a function, the name of the function is written, followed by the opening parenthesis, the
list of zero or more parameters, and finally, the closing parenthesis. If the number of
arguments when calling a function is greater than the number of parameters, the extra
arguments are ignored. If there are less arguments than parameters, the missing arguments
are substituted with undefined.
Although the function declaration can be below the call, it is recommended to declare all
functions before you call them.
A function naming convention in JavaScript is that the first letter of the function name should
start with a lowercase letter. You can find more code and naming conventions at
http://javascript.crockford.com/code.html.
Functions can be referenced by variables, array entries, and properties of other objects, can
be declared with
ith literals,
literals and can even
e en be passed as arguments
arg ments to ffunctions.
nctions They
The can be
returned as values from functions as well. In summary, functions can be used anywhere that
you might use a variable.

JavaScript and HTML5: Develop Web Applications 3 - 49


Anonymous Functions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var multiply = function (x, y) {


var result = x * y;
return result;
};

n s e
multiply(135, 6);
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
When k as a
function does not have a name, it is an anonymous function. Anonymous functions
u
areVcommonly used for inline callbacks to other functions and object methods.
l a n
Mi You can assign the function to a variable the same way you would assign values to variables.
By attaching a variable name to a function, you can call the function. The snippet of code in
the slide shows the function expression of an anonymous function that is assigned to the
variable multiply.

JavaScript and HTML5: Develop Web Applications 3 - 50


Calling a Function

• Function as a method:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var myObj = {
name: "Hello World!",
print: function(message) {
console.log(this.name + message);
}
}; // i.e. myObj.print(' JS Robot');
• Function as a constructor: s e
ce n
function Tree(type, height) {
el i
this.type = type;
a b l
this.height = height; fe r
a n s
}
n - tr
Tree.prototype.getType = function() { o
return this.type;
s an
}
) h a deฺ
ฺrs t Gui
var myTree = new Tree("Big Leaf Maple", 80);
s
myTree.getType(); em uden
// "Big Leaf Maple"
@
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s about the different ways to call a function, it is important to mention the
Beforektalking
V u
invocation context; functions always have one at the time they are called. The value of the
l a n
Mi this keyword represents the invocation context. The implicit parameter this is also passed
to the function.
Options to Call a Function:
1. As direct invocation: The first option was shown in a previous slide where the
multiply function was called: var total = multiply(135,6);. Alternatively, it can
be without being assigned to a variable: multiply(135,6);. It is a regular function
invocation, and is invoked directly. In this type of call, the this value is generally the
global object (the window object).
object)
2. As a method: An object’s property value can also be a function. The first code in the
slide shows how to call a function that is assigned to a property in an object. When
using this type of call, the this value represents the object.
3. As a constructor: To invoke the function as a constructor, precede the function with
the new keyword. The purpose of calling a function as a constructor is different from the
p
other options. Its p
purpose
p is more to initialize a new object
j to initial conditions by
y using
g
the this keyword as shown in the second code in the slide. This type of call makes use
of the fact that functions inherit from Function.prototype, which in turn inherits from
Object.prototype.

JavaScript and HTML5: Develop Web Applications 3 - 51


Calling a Function

• Self-invoking:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

(function() { // Executed immediately })();

• The arguments variable


n s e
function sum() {
lice
var total = 0;
a b le
for (var i= 0, l = arguments.length; i < l; i++)
s f er {
total += arguments[i];
- t r an
}
n on
return total;
s a
} h a deฺ
s ฺrs) t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
It is a common convention for constructors to capitalize the first letter of the function name.
u
V
i l anConstructors and the keyword new were introduced in the previous topic “Creating Objects,”
M where prototyping was introduced as well.
4. Self-invoking: You can specify that functions invoke themselves by appending
parentheses to the function declaration, as shown in the slide.
The arguments variable
All the arguments of a function are available through the arguments object. This object has a
length property, which is the number of received arguments. An example of usage of the
arguments
g variable is shown in the code in the slide.
Note that JavaScript does not check the type of the argument values passed in a function.

JavaScript and HTML5: Develop Web Applications 3 - 52


Recursion

• Recursion to get the factorial of a number:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function factorial(number) {
if (number < 2)
return 1;
return number * factorial(number - 1);
}

n s e
ice
• Recursion to get the Fibonacci of a number:
b l el
fe r a
a n s
-tr
function fibonacci(number) {
o n
return (number < 2) ? number: fibonacci(number
n - 1) +
fibonacci(number - 2);
s a
} h a deฺ
s ฺrs) t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
A function can also call itself. In this case, it is a recursive function. In the slide, two functions
u
V
are displayed: one to get the factorial of a number by using recursion and another to get the
an
Mil Fibonacci of a number.

JavaScript and HTML5: Develop Web Applications 3 - 53


Scopes

Try window.x in JSConsole.


• Global Scope:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var x = "I am a global var!";


function printVar()
{
console.log(x);
}

n s e
• Function scope: ice
b l el
function declareVariable() {
f er a
if (t
(true)
) {
an s
- t r
var x = "Declared in a block of code";
n on
}
s a
console.log("Value of x: " + x);
) h a
i d eฺ
} ฺrs u
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks there is a function scope and a global scope, but not a block scope (statements
In JavaScript,
u
V with curly braces).
ndelimited
a The Global Object
Mil
If a variable is not defined inside a function, as shown in the first code in the slide, it has a
global scope. These kind of variables are stored in the global object window (when using a
browser).
Function Scope
In a function scope, if a variable is declared in a block of code, like a for or at any position
inside a function, the variable would still be visible within the function in which it is declared. It
is recommended that you declare variables at the top of the function. Variables defined within
the function are not visible outside of the function.
An example of function scope is shown in the second code in the slide, where the variable x
is declared in the if block, but is still visible in the function.

JavaScript and HTML5: Develop Web Applications 3 - 54


Example: Functions

Use the JSConsole web application and run the following


example to see how to define and call functions, function
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

methods, recursion, function scope, inner function, and closure.

Ti
Time Li
Limit:
it 10 minutes
i t

n s e
ice
b l el
f er a
T
Try this
thi s
an section
ti
n - t r
inoJSConsole.
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksthe output of the code on the Console tab.
Observe
u
Vcode in JSConsole is the same as in the slides. You can refer to the slides at any time
l a n
The
Mi while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 3 - 55


Where Can I Learn More?

Resource Website
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

ECMAScript Language
http://www.ecma-international.org/ecma-262/5.1/
Specification 5.1 Edition
Douglas Crockford's
Crockford s
http://javascript.crockford.com/
JavaScript
Mozilla Developer Network https://developer.mozilla.org/en-
– JavaScript reference US/docs/Web/JavaScript/Reference
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 56


Summary

In this lesson, you should have learned how to:


• Write JavaScript code to:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Declare variables
– Create an object
– Create and call a function
– Create and iterate arrays
• Write JavaScript arrays to store data n s e
ice
• Define JavaScript objects as a b l el
key-value
y store fe r a
a n s
• Access the properties of an object by n - tr
o
using get and set
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 3 - 57


Practice 3: Overview

This practice covers the following topic:


• Practice 3-1: Passing JavaScript Tests in JSConsole with
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Jasmine

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n mil to u
(
In this k a
s you create variables, objects, and functions to pass test cases. In JSConsole,
practice
u
anyouVwrite JavaScript code to pass the prebuilt test cases.
Mil

JavaScript and HTML5: Develop Web Applications 3 - 58


4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Combining
C bi i HTML5 and d
JavaScript in Web Applications ice n s e
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

HTML5 and Style Dynamic Data


Introduction Document Applications with AJAX and
Object Model with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
s an Day

) h a deฺ
s ฺrs t Gui Hands-On Practice

@ em uden Lecture

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 2


Objectives

After completing this lesson, you should be able to:


• Create HTML5 documents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Create HTML5 forms to request information and


process it
• Validate HTML5 forms input
• Write JavaScript functions for
HTML5 events n s e
ice
• Manipulate HTML5 elements through DOM b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 3


Topics

• HTML5 Documents
• HTML5 Forms
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Reading Data from Forms


– Validating HTML5 Form Input
– Sending Data from Forms
• Controlling HTML5 Events with JavaScript
– Writing onClick Events n s e
ice
• Document Object Model (DOM) b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 4


HTML5 Documents

Basic HTML5 Structure:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My HTML5 page</title>
<link rel="stylesheet" href="styles.css">
n s e
<script src="script.js"></script>
lice
</head>
a b le
<body>
s f er
<h1>My
h1 M fi
first
t HTML5 page</h1>
/h1
- t r an
<p>This is a paragraph</p>
n on
<!–- comment -->
s a
</body>
) h a
i d eฺ
</html> ฺrs u
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n mil to u
(
In this k a
s HTML5 and HTML have been used to mean the same thing, because we are
lesson,
V u
nconsidering HTML5 as version 5.0 of the HTML syntax.
a The HTML5 documents consist of a tree of elements and text that describe interactive
Mil
content. HTML5 defines new tags for the different sections of an HTML document.
The basic structure of an HTML document is shown in the slide.
Open the example “HTML5 Sections” for this lesson in JSConsole and watch this page
example with the elements that are described as follows.
In HTML5, it is enough if you enter <!DOCTYPE html> in the first line. This line tells the
browser the specification that should try to follow, which is HTML5 in this case.
Following the DOCTYPE element is the <html> tag, which represents the root of the
document. Inside the <html> tag, you have the <head> and <body> tags.
Under the <head> tag, you can find all metadata for the document. The example in the slide
shows some elements inside the head element:
• The <meta> tag specifies some metadata. In this case, the parameter charset is
declaring
g the character encodingg to use when storingg or transmitting
g the document.
Notice that this tag does not have an end tag.

JavaScript and HTML5: Develop Web Applications 4 - 5


• The <title> tag specifies the title or name of the document. It is recommended to
always have a title because this is used by search engines.
• The Link element, which is represented with the <link> tag in the document, creates
a relation or link of the current document with another document.
- The href attribute specifies the destination of the link. In the example, it is the
styles.css file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

- The rel attribute dictates the type of relation between the document and the
resource. In this case, the referred file is a style sheet for the document.
• The <script> tag includes dynamic scripts in the document. When a script is included,
the browser generally runs the script uninterrupted before continuing to parse the
document.
- With the src attribute, the script is imported from an external file (script.js in
the example) instead of typing the code inline.
n s e
- The type attribute specifies the language of the script. If it is absent, as in the
ice
example, the default is used, which is "text/javascript“.
b l el
r a
The official validator of an HTML document is found at the following URL: http://validator.w3.org/.
fe
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 6


HTML5 Sections

<header>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<section>
<header>
h d
<article>
<nav> <aside> n s e
<footer> ce
el i
<header> a b l
fe r
<article> a n s
n - tr
o
<footer>
s an
) h a deฺ
ฺrs t Gui
<footer>
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks element represents the content of the document. Under the <body> tag, the
The body
u
V can be divided into different sections. HTML5 presents new sectioning elements.
content
l a n
Mi Some of these elements are header, nav, article, footer, header, aside, and
section.
The diagram in the slide shows an example of the layout of an HTML5 page with the
mentioned elements. The example is just one of multiple variations for web page layouts.
The <header> and <footer> represent information that goes at the beginning and at the
end of a page or an article, respectively. In the header element, the headlines, company
logos, and navigational links are usually included. The footer element usually contains
copyright,
i ht author
th iinformation,
f ti or related
l t d lilinks.
k
The <section> tag defines a section of the document. In this context, a section is a thematic
grouping of context. Examples of sections in a website of an event are the introduction, the
countdown, the speakers, the schedule, and so on.
Note: It is not recommended to use <section> as a generic container, because <div> is
still used for that purpose.

JavaScript and HTML5: Develop Web Applications 4 - 7


HTML5 Sections
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
The <article> tag represents a self-contained piece of content on a web page. One of the
u
Vfeatures of an article element is that it is distributable or reusable. An article can be used,
key
l a n
Mi for example, for syndication.
The <nav> tag contains navigation links. It is the section of a page that links to other pages or
to other areas within the current page.
The <aside> tag represents content that is tangential to the current content. Often, aside
sections are represented as sidebars. Aside content is used, for example, for pull quotes,
advertising, and generally for content that is considered separate from the main content of the
web page.
The example in the slide shows an example of an HTML5 page with the sectioning elements
mentioned in the preceding paragraphs.
For more details on these section elements and other elements of HTML such as grouping,
text-level semantics, or embedded content, go to the following link:
http://www.w3.org/TR/html5/semantics.html#semantics.

JavaScript and HTML5: Develop Web Applications 4 - 8


Example: HTML5 Document Sections

Use the JSConsole web application and run the following


example to see the different tags used in HTML5 to define the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

areas in a document.

Ti
Time Li
Limit:
it 5 minutes
i t

n s e
ice
b l el
er a
Tryathisn sf section
sectio
t r
-JSConsole.
n oin
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Click the Preview tab to see how the browser renders the different HTML5 tags.
u
V
i l anThe code in JSConsole is the same as in the slides. You can refer to the slides at any time
M while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 4 - 9


Topics

• HTML5 Documents
• HTML5 Forms
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Reading Data from Forms


– Validating HTML5 Form Input
– Sending Data from Forms
• Controlling HTML5 Events with JavaScript
– Writing onClick Events n s e
ice
• Document Object Model (DOM) b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 10


Reading Data from HTML5 Forms
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s a web page has form controls, such as text fields, buttons, check boxes, range
A formkon
u
V or color pickers. The user interacts with the form, providing data that is sent to the
ncontrols,
a server for further processing.
Mil
You will now try building a form that collects proposals (abstracts) for the next big conference
of developers that is being organized. You will need to gather some personal information, and
of course, the abstract.
The form Element
The <form> tag specifies the form that contains controls for collecting user input that can be
submitted to a server for processing.
The form element in the example in the slide contains two attributes: the name of the form and
the action attribute that specifies the URL of the script that will process the form request.
The action attribute is an attribute for form submission. The value of the action attribute in
the example is “#,” which leads to the same page and does nothing; in a later topic, this
attribute is reviewed in detail.
The form can also have an ID. The ID is useful when there are form elements that are out of
the <form>
f tag but belong to the form.
form This can be done by adding the form="myFormId"
f " F Id"
attribute to those elements that you want to be part of the form, even when they are not under
the <form> tag.

JavaScript and HTML5: Develop Web Applications 4 - 11


The form Elements

<form name="proposalForm" action="#">


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<fieldset>
<p>
<label for="name">Name:(required)</label>
<input type="text" name="name" id="name">
</p>
<p>
<label for="email">Email:(required)</label>
<input type="email" name="email" id="email">
</p>
<p>
n s e
<label for="telephone">Telephone:</label>
ice
<input type="tel" name="telephone" id="telephone">
b l el
</p>
<p><label for="abstract">Abstract:(required)</label></p>
fe r a
<textarea rows="5"
rows "5" cols="80"
cols "80" name
name="abstract"
"abstract" id
id="abstract"></textarea>
"abstract"></textarea>
a n s
-
<p><label for="file">Or you can send us a document with the
n tr
abstract:</label></p>
o
<input type="file" name="file" id="file">
s an
) h a deฺ
<p><input type="submit" name="submit" value="submit"></p>

ฺrs t Gui
</fieldset>
</form>
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks in the slide shows the code of the form that was shown in the previous slide. The
The code
u
V “HTML5 Forms” for this lesson also contains the code.
example
l a n
Mi The code in the slide shows a form element, a fieldset element, multiple input and label elements, and a textarea element. There are also some paragraph <p> elements to
arrange the label and input elements properly.
The fieldset Element
The <fieldset> tag groups related form controls and labels.
Form Labels
The <label> tag represents a caption
caption, and can be associated with a specific form control
control. In
the example, there is a label for each input and textarea element. The for attribute
indicates the control that is associated with the label.
The input, textarea, and other controls can be written as descendants of the label
element (inside the <label> tag). However, in the example, they are separated for better
handling of the elements.

JavaScript and HTML5: Develop Web Applications 4 - 12


HTML5 Form Input Types
The <input> tag has several types and HTML5 has introduced new input types. The input
element allows a user to edit data. It contains several attributes. Some attributes of the input
element include:
• The type attribute specifies the type of data and the control to be used. The default
value is the Text type.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• The value attribute provides the default value of the element.


• The name and id attributes are also two typical attributes in the input element, in
order for the element to be identifiable and linked to other elements. These two
attributes may,
y, but do not have to,, be the same.
input elements can be disabled, but in this case, the values cannot be modified.
The input element has several types. Some of them are as follows:
• Hidden: An <input type="hidden" value="hidden value"> tag is not displayed n s e
i ce
el
in the browser.
• Text: This type is the default. The syntax is <input type="text">. An example is a b l
fer
shown in the form that is used in this section.
a n s
n - tr
• Telephone: The tag <input type="tel"> allows validation and integrated support for
o
an
entering telephone numbers.

h s
• URL: The control <input type="url"> allows you to edit a single absolute URL.
a deฺ
)
ฺrs t Gui
• E-mail: The syntax is <input type="email">. An example is shown in the form that
s
is used in this section.
@ em uden
• Password: The <input
a n t
p type="password">
yp
S p tag
g creates an input
p text field but the
s
uk e thi s
characters that are entered in the text field are displayed as asterisks or bullets, in order
ฺ v
an
to hide this information.
s
n (mil to u
• Date: The syntax is <input type="date">, and allows you to enter a date in date

ksa
format.
V u
• Time: The syntax is <input type="time">, and allows you to enter a time in time
an
Mil
format.
• Number: The <input type="number"> tag is used for specifying a numerical value.
• Range: With the <input type="range"> tag, the control renders as a slider in most
browsers, thus allowing a different way to enter a numerical value, by adjusting the
slider.
• Color: The tag <input type="color"> creates a color picker for selecting a color
value.
• Checkbox:
Ch kb Th tag
The t <input
i " h kb " renders
type="checkbox"> d a control
t l with
ith two
t states:
t t
selected or deselected.
• File Upload: The syntax is <input type="file">. An example is shown in the form
that is used in this section.
• Search: With the <input type="search"> tag, a text field control is rendered, with
the difference that a small “x” appears when entering content that allows you to clear the
field.

JavaScript and HTML5: Develop Web Applications 4 - 13


• Submit: The <input type="submit"> tag represents the button for submitting a
form. An example is shown in the form that is used in this section.
• Reset: The <input type="reset"> tag represents the button which, when activated,
resets the form.
• Button: The <input type="button" value="button"> tag represents the button
with no default behavior.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
i ce
b l el
fer a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 14


input Attributes

• <input type="text" maxlength="30">:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• <input type="text" value="You cannot write here" readonly>:

• <input type=text list=suggestions>


<datalist id=suggestions>
n s e
ice
el
<option value="Maybe this entry">
<option value="Or this one">
a b l
fe r
/
</datalist>
a n s
o n -tr
s an
) h a deฺ
• <input type="email" placeholder="email@example.com">:

s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
• ks a and minlength: They limit the number of characters that a user can input.

umaxlength
V readonly: This controls whether or not the user can change the value of the form
an
Mil ee e t
element.
• required: This specifies that the input field must be filled out to submit a form. This
attribute is explained in detail when form validation is discussed.
• list: With this attribute, the element lists predefined options to the user.
• placeholder: With this attribute, the input field has a prefilled value that disappears as
soon as the user begins typing. It is recommended that you do not overuse this attribute,
thinking it to be a replacement of the label element, because it can reduce the
accessibility and usability of the control. It is recommended that you put this information
in label instead of placeholder.
To read more about the input element and its types and attributes, look at:
http://www.w3.org/TR/html5/forms.html#the-input-element.

JavaScript and HTML5: Develop Web Applications 4 - 15


Validating HTML5 Form Input
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s easiest ways to validate form input is with the required attribute. When adding
One ofkthe
u
Vattribute to the input or other HTML form elements, you are asking the browser to make
this
l a n
Mi sure that the field is filled out before the form is submitted.
The screenshots in the slide show the messages that are shown to the user when filling a field
is mandatory before submission. The appearance of error messages varies depending on the
browser used. However, CSS can be used to change the style of these messages. There are
four CSS pseudo classes for forms that can be used: :optional, :required, :valid, and
:invalid. CSS is detailed in the lesson titled “Style Applications Using CSS3 and
JavaScript.”
Another attribute that is useful for validation is the pattern
tt attribute to use JavaScript
attribute,
regular expressions to specify the pattern that an input should follow before submission.
Regular expressions are covered in the lesson titled “The JavaScript API.”
The example “HTML5 Form Validation” for this lesson contains the example code for the
submission form with the validated input fields.
The novalidate and formnovalidate boolean attributes can be used to disable
validation for the form during submission. The novalidate attribute is used on form
elements and the formnovalidate attribute on submit input elements.
A constraint validation API is also available so that scripts can customize behavior on
validation. It can be read at http://www.w3.org/TR/html5/forms.html#the-constraint-validation-api.
JavaScript and HTML5: Develop Web Applications 4 - 16
Sending Data from Forms

<form action="/JSConsole/FormSubmissionServlet" name="proposalForm"


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

method="post" enctype="multipart/form-data">
<fieldset>
<label for="name">Name:(required)</label>
<input type="text" name="name" id="name">
<label for=
for="email">Email:(required)</label>
email >Email:(required)</label>
<input type="email" name="email" id="email">
<label for="telephone">Telephone:</label>
<input type="tel" name="telephone" id="telephone">
<label for="abstract">Abstract:(required)</label> n s e
ice
el
<textarea rows="5" cols="80" name="abstract"
id="abstract"></textarea>
a b l
<label>Or you can send us a document with the
fe r
abstract:</label>
b t t /l b l
a n s
n - tr
o
an
<input type="file" name="file" multiple>

h s
<input type="submit" name="submit" value="submit">
a deฺ
</fieldset>
)
ฺrs t Gui
</form>
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
In the forma
s to send the abstract for the conference, you have added three new attributes:
u
V method, and enctype.
action,
l a n
Mi The action /JSConsole/FormSubmissionServlet attribute specifies the location of
action="/JSConsole/FormSubmissionServlet"
the Java Servlet, which is the destination for the form data.
The method attribute specifies the HTTP method to send the form data to the server; in this
example, its value is "post", which means that the form data will be enclosed in the body of
the message and sent to the server. The POST method is the common method that is used
when using forms.
The enctype="multipart/form-data" attribute specifies the structure that the data will
be converted to. This type of encryption is always used when you are sending binary data.
There is also a new attribute in the input file element: multiple. When you set this attribute,
you can select and send multiple files.
The example “HTML5 Form Submission” for this lesson contains the example code for the
submission form that is shown in the slide, and also the code for the Java Servlet. The
FormSubmissionServlet servlet prints on the screen the names and values of the
parameters that are sent in the form
form. In the case of a file
file, it prints the content of the file
file.

JavaScript and HTML5: Develop Web Applications 4 - 17


Examples: HTML5 Forms

Use the JSConsole web application and run the following three
examples to see how to work with HTML5 Forms.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 10 minutes

n s e
ice
Try this section b l el
f e ra
i JSConsole.
in JSConsole
a ns
n - t r
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Interact with the form on the Preview tab to see the validation of input fields or how you can
u
V
select multiple files when submitting a form.
anThe code in JSConsole is the same as in the slides. You can refer to the slides at any time
Mil
while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 4 - 18


Topics

• HTML5 Documents
• HTML5 Forms
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Reading Data from Forms


– Validating HTML5 Form Input
– Sending Data from Forms
• Controlling HTML5 Events with JavaScript
– Writing onClick Events n s e
ice
• Document Object Model (DOM) b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 19


Controlling HTML5 Events with JavaScript

1. Event handling in HTML elements using attributes:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<section id="section-1" onclick="showSpeakersBanner()">

2. Event handling from JavaScript and DOM:


document.getElementById("section-2").onclick =
showWorkshopBanner;

3. Event handling by adding an event listener: n s e


ice
window.addEventListener("load", function() { b l el
alert("Window load event listener fired!"); fe r a
a n s
-tr
}, false);
o n
s an
document.getElementById("headerProposal").addEventListener(
"click", showAbstractBanner, false);
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks handlers, the HTML5 application can detect an event (that is, the user clicks some
With event
u
V and call a JavaScript function. Event handlers are listeners that are registered with
element)
l a n
Mi HTML5 elements and that implement a function that responds to these events. The name of
these event handlers start with “on,” followed by the event name. In the slide, three ways of
adding event handling to HTML5 elements are shown:
1. Event handlers as attributes of the HTML elements: The disadvantage with this
approach is that code is written for every element and there is no a centralized control.
2. Event handlers from JavaScript: Here the event handler declaration is in the
JavaScript side (in the code.js file for the given example) and it uses Document
Object Model (DOM is detailed in a later topic in this lesson)
lesson). In the example in the slide
slide,
the showWorkshopBanner function is registered as the function to call when the user
clicks the workshop section (with id="section-2" in the HTML document) on the web
page.
3. Attaching event listeners to the HTML element: With this approach, an unlimited
number of events can be attached to any single element. In the example in the slide, two
examples of addEventListener have been provided. The third parameter in this
method controls how the listener reacts to bubbling events.

JavaScript and HTML5: Develop Web Applications 4 - 20


When an event propagates, it is fired on the parent elements. Bubbling events are those that
are handled or executed from inner elements to outer elements when you have nested
elements. Capturing events go in the opposite direction: events are handled from outer to
inner elements.
The example “HTML5 Events” for this lesson contains the example code that is shown in the
slide. You can also open the Next Big Conference web page. When a user clicks the three
sections, some banners (alerts) are displayed.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Read more about the event handlers that are supported by HTML elements at:
http://www.w3.org/TR/html5/webappapis.html#event-handlers-on-elements,-document-
objects,-and-window-objects.
To read more about event handlers in general, see: http://www.w3.org/TR/html5/single-
page.html#event-handlers.

n s e
i ce
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 21


Example: HTML5 Events

Use the JSConsole web application and run the following


example to see how to handle events.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 5 minutes

n s e
ice
b l el
er a
Tryathisn sf section
sectio
t r
-JSConsole.
n oin
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Interact with the page on the Preview tab to see the different events that are triggered when
u
V
you click different parts of the document.
anThe code in JSConsole is the same as in the slides. You can refer to the slides at any time
Mil
while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 4 - 22


Topics

• HTML5 Documents
• HTML5 Forms
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Reading Data from Forms


– Validating HTML5 Form Input
– Sending Data from Forms
• Controlling HTML5 events with JavaScript
– Writing onClick Events n s e
ice
• Document Object Model (DOM) b l el
er a
Tryathisn sf section
sectio
t r
-JSConsole.
n oin
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 4 - 23


DOM Tree
html
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

head body

title header section aside footer

meta h1 h2 nav article h1 p

n s e
link
ice
ul header p
b l el
script fe r a
a n s
h1
n - tr
o
s an
) h a depฺ
ฺrs t Gui
li li li li p p p
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks Object Model (DOM) refers to conceptualization of a document and its contents,
Document
u
V gives structure to the document.
which
l a n
Mi DOM was created by the W3C with the objective of standardizing the web by describing how
an application can interact with and access the structured document. It defines the objects,
methods, and properties that are required to handle the document.
DOM Tree
The document with DOM is expressed as an in-memory representation of a document, like a
family tree, where there are hierarchies and relationships between family members. Concepts
such as parent, child, and sibling between the tree elements can be seen in a document.
Open the index.html file in the example “HTML5 Sections” for this lesson while matching
the DOM tree in the slide.
The root element is the <html> tag. This is the parent element for all elements in the
document. One level deeper, you find the <head> and <body> tags. These two tags are
siblings, with <html> as the parent. Both are children of <html>.
Relationships such as parent, child, or sibling between elements in the document are applied
to all the current elements. For example, <article> has <section> as its parent and has
five children: the <header> tag, and four <p> tags.

JavaScript and HTML5: Develop Web Applications 4 - 24


Levels of DOM Specifications
DOM has levels 0, 1, 2, 3, and 4. The levels are related to the updates of the DOM
specification. However, not everything is updated when upgrading from one level to another.
That is why in the example, there are some specifications at level 2 that are still valid because
they are not covered in the upper levels. For a better understanding of DOM levels, read the
DOM Technical reports at http://www.w3.org/DOM/DOMTR. The DOM objects, methods, and
properties detailed in this course are from level 3.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
i ce
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 25


DOM Tree Nodes

html
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

head

title

meta n s e
ice
b l el
link
fe r a
a n s
o n -tr
script
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks on the left in the slide shows the tree structure of the branch (on the right) from
The diagram
u
theVpreceding HTML document. This is done by using Live DOM Viewer at
l a n
Mi http://software.hixie.ch/utilities/js/live-dom-viewer/. Notice that Text nodes are included.
The DOM tree includes several kinds of nodes, the most common of which are the
DocumentType node, Element nodes, Text nodes, and Comment nodes. The first three
types mentioned are shown in the diagram in the slide.
Notice in the diagram in the slide that each element in the DOM tree is represented by an
object (DOCTYPE, HTML, HEAD, #text, BODY, H1, H2, and so on). Because the objects are
instances of interfaces, they have APIs so that they can be manipulated (remove, add,
replace,
l notify
tif events,
t and d modify).
dif ) DOM makes
k the
th HTML5 d documentt a live
li ddocument.t
DOM Tree Accessors
For a better understanding of subsequent topics, you need to make a stop here and review
the document.getElementByID method. This method is part of the Document node, and
returns only one element that has an ID attribute with the given value.

JavaScript and HTML5: Develop Web Applications 4 - 26


The Node Object
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks in the DOM tree extends and inherits properties and methods from the Node
Each element
V u
object.
l a n
Mi Open the index.html page of “HTML5
HTML5 Sections”
Sections for this lesson in JSConsole. The URL for
this page is: http://localhost:8080/JSConsole/view/lesson04/html5_sections/index.html. In
Firefox, after you have opened the page, go to Tools > Web Developer > Firebug > Open
Firebug, and click the Console tab to see the console.
Properties or Attributes of the Node Object
nodeName: This is the name of the node. For example, if you type
document.firstChild.nodeName in the console, you will get “html,” because
<!DOCTYPE html> is the first node for the document. The table in the next slide shows the
values of nodeName according to the node types.
nodeType: This is the numeric code that is associated with the type of node. If you type
document.firstChild.nodeType in the console, it returns 10. The constant names and
numeric values associated with each type of node are shown in the next slide.
nodeValue: This is the value associated with a Node. However, this property is not the text
inside an element
element. This is a common mistake that is made
made. Only for an Attr
Att node will it be
Attr.value of the node. For the CDATASection, Comment, ProcessingInstruction,
and Text nodes, it will be the content of the nodes. It will be null for any other type of node.

JavaScript and HTML5: Develop Web Applications 4 - 27


Node Names
Type of Node nodeName
Attr Attr.name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

CDATASection "#cdata-section"
Comment "#comment"
DocumentFragment "#document"
Document "#document-fragment"
DocumentType DocumentType.name
n s e
Element Element.tagName
ice
Entity entity name b l el
fe r a
EntityReference name of entity referenced
a n s
Notation notation name o n -tr
s an
ProcessingInstruction.target
ProcessingInstruction
) h a deฺ
Text "#text"ฺrs
s G ui
e m dent
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
• sa n( References the single direct parent. For example, if you type
u k
parentNode:
V document.body.parentNode in the console, the result would be <html>, because
an
Mil •
<html> is the parent node of <body>.
childNodes: Is the list of nodes that are all children of this node. For example, if you
type document.body.childNodes in the console, it returns a NodeList with all the
children nodes of <body>. To refer to a specific child node, you can type
document.body.childNodes.item(x), where x is the index of the node in the
array list, starting from 0. Another option is to type document.body.childNodes[x].
• previousSibling: Is the node that precedes this node. For example, typing
document body previousSibling in the console would return a TextNode with
document.body.previousSibling
the text content "\n" (new line), although you could think that it is <head>. (Remember
that new lines are included as Text nodes in the DOM tree.)
• nextSibling: Is the node that follows this node
• firstChild: Is the first child of this node. It is equivalent to childNodes[0].
• lastChild: Is the last child of this node

JavaScript and HTML5: Develop Web Applications 4 - 28


Methods
• hasChildNodes: This method returns true if the node has any children. Otherwise it
returns false.
• hasAttributes: This method returns true if the node (only Element nodes can
have attributes) has any attributes. Otherwise it returns false.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
i ce
b l el
fer a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 29


Node Types

Constant name Node Type Short value


ATTRIBUTE_NODE Attr 2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

CDATA_SECTION_NODE CDATASection 4
COMMENT_NODE Comment 8
DOCUMENT FRAGMENT NODE
DOCUMENT_FRAGMENT_NODE DocumentFragment 11
DOCUMENT_NODE Document 9
DOCUMENT_TYPE_NODE DocumentType 10
n s e
ice
el
ELEMENT_NODE Element 1
a b l
ENTITY_NODE Entity 6
fe r
n
a5 s
o n -tr ENTITY_REFERENCE_NODE EntityReference
NOTATION_NODE Notation
a n 12

h a s eฺ
ProcessingInstruction 7
PROCESSING_INSTRUCTION_NODE
r s ) u i d

sText tG 3
TEXT_NODE
e m e n
a n @ Stud
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks in the slide shows the types of nodes that are identifiable through the nodeType
The table
u
V This attribute is an unsigned short value, although there are constants also in the
attribute.
l a n
Mi Node object, so that you can identify the type of node by constant name or by numeric value.

JavaScript and HTML5: Develop Web Applications 4 - 30


The Element Node
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks node is built on top of the Node object. It represents the elements delimited by
The Element
u
theVstart tags and end tags in an HTML or XML document. The diagram in the slide shows a
l a n
Mi part of the DOM tree of the example document that you have been using in this topic (http://localhost:8080/JSConsole/view/lesson04/html5_sections/index.html).
In the diagram, you can see the element names (or tagName) in uppercase and in font color
purple.
• tagName: This is an attribute of the Element node that contains the name of the
element.
Methods of the Element Node
• getAttribute: Allows you to retrieve an attribute by sending the name of the attribute
as the parameter
• setAttribute: Adds a new attribute by sending the name and value of the attribute to
add as parameters. If the specified attribute already exists, only the value is set or
changed.
• removeAttribute: Allows you to remove an attribute by sending the name of the
attrib te to remove
attribute remo e as the parameter
• getElementsByTagName: Returns a NodeList with all the elements that match the
given tag name. To retrieve all the elements, you can use
getElementsByTagName('*').
JavaScript and HTML5: Develop Web Applications 4 - 31
The document Object
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksHTML tab in the Firebug window that you opened in your browser. You will see the
Click the
u
tagVtree that is similar to the figure in the slide.
l a n
Mi The document object comprises the opening <html> tag and the closing <html> tag, including the children tags, and even more, because it includes the DocumentType node
(<!DOCTYPE html>). In summary, document represents the entire document. It is the root of
the DOM tree, and is the entry point to the web page’s content.
The document object implements the Node interface, so all DOM core properties and
methods are available in the document object.
HTMLDocument (defined in the DOM Level 2 HTML specification) is an object that
implements the Document and HTMLDocument interfaces, and is specific to deal with HTML
documents.
Methods
document.getElementById: Returns the element that has an ID attribute. The ID is
provided as a parameter to this method. It returns only one element. For example, if you call
the following method in the console: document.getElementById("section-1"), it
would return the <section>
ti element
element.
getElementsByTagName: Returns an HTMLCollection of all elements with the given tag
name. The order of elements in the HTMLCollection is determined by their order in the
DOM tree.
JavaScript and HTML5: Develop Web Applications 4 - 32
Other Element Nodes
DocumentType
node
Text node
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
Attr nodes ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Attr Node
u
V nodes are not considered independent nodes in the DOM tree (as seen in the figure in
l a n
Attr
Mi the slide). They are part of the Element object. Notice that the attribute name is in lowercase.
With the Node.attributes property, you can get the attributes of the node. For example,
typing document.getElementsByTagName("LINK")[0].attributes in the console
would return the following NamedNodeMap: [href="style.css", rel="stylesheet"].
To get a specific attribute, the getAttribute method is used:
document.getElementsByTagName("LINK")[0].getAttribute("rel") returns
"stylesheet".
The most common uses of attributes are to give the element an ID, or to carry some data with
data-*, among others.
DocumentType Node
The doctype node is read-only and the attribute name returns its name. In the example, the
name of doctype is "html" (document.doctype.name).

JavaScript and HTML5: Develop Web Applications 4 - 33


The window Object
• The window object represents the browser window itself that contains the DOM
document. It is JavaScript’s global object.
The specification of the window object is not in the DOM specifications; it is in the HTML5
specification: http://www.w3.org/TR/html5/browsers.html#the-window-object.
The Text Node
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

This node represents, as its name says, the text in the document. In the figure in the slide,
you can see the Text nodes, with #text as the node name, followed by the content of the
Text node. In this example, you could get the text “The Next Big Front-End Conference”
under <title> with one of the following
g commands in the console:
• document.getElementsByTagName("title")[0].childNodes[0].textContent
• document.getElementsByTagName("title")[0].childNodes[0].wholeText
• document.getElementsByTagName("title")[0].childNodes[0].data
n s e
• i ce
el
document.getElementsByTagName("title")[0].childNodes[0].nodeValue
The Comment Node
a b l
fe r
This node represents the content of a comment
a n s
comment. The node name for this node is #comment.
#comment

n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n ( mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 34


Accessing and Manipulating Elements

• createElement:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var newParagraphElement = document.createElement("p");


var text = "This is the new Text";
var newTextElement = document.createTextNode(text);
newParagraphElement.appendChild(newTextElement);
P hEl t dChild( T tEl t)
• replaceChild:
parentNode.replaceChild(newParagraphElement, n s e
ice
currentParagraphElement);
b l el
• removeChild: fe r a
a n s
n o n-tr
parentNode.removeChild(currentParagraphElement);
• cloneNode: a
s eฺ
h a
var clonedNode =
ฺ r s ) u id
ms dent G
currentParagraphElement.cloneNode(true);
e
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks you to alter the structure of the document, create new elements, and add, edit,
DOM allows
u
Vremove the nodes of the DOM tree.
and
l a n
Mi Open the example “DOM DOM Manipulation”
Manipulation from the examples for this lesson. The code shown in
the slide is from that example. In the example, you find a series of buttons to work with a
paragraph on the web page: you can replace, remove, duplicate, or insert new text.
Adding a node to the DOM tree is a two-step process:
1. Create the new element. An example of the code is shown in the first code in the slide.
2. Insert the element into the node tree.
For the first step,
step the two methods that are available in the document object are
createElement and createTextNode.
For the second step, some of the methods that are available in the Node object are:
• appendChild: This adds a node to the DOM tree. In the example, a new text element
is added as a child of a new paragraph element.

JavaScript and HTML5: Develop Web Applications 4 - 35


• insertBefore: Instead of adding the node at the end of the list of child nodes, with
this method, you have the option to choose the exact location where you want the node
to be inserted. With an extra parameter, you can specify before which element you want
to insert the new node.
• replaceChild: This does not remove the node; instead, it replaces the child node with
a new one. It returns the old child node.
• removeChild: This removes the child node from the list of children nodes.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• cloneNode: This returns a duplicate of the node. With its parameter, it is possible to
specify if the node is duplicated with all its child nodes or not. In the example in the
slide, this parameter is set to true because you want the child node of the paragraph
element;
l t otherwise,
th i th
the paragraphh wouldld bbe cloned
l d without
ith t ttextt and
d nothing
thi iis di
displayed
l d
on the web page.
Alternatives for Modifying the Content of the Document
1. Element.innerHTML: This is an extension to the Element interface, and represents n s e
i ce
the markup of the element’s contents. This attribute is popular because unlike DOM
b l el
methods, you do not have to build the contents to modify an element.
fe r a
The way innerHTML works is by allowing access to the browser’s
a n s
browser s HTML parser
parser, to
serialize and deserialize strings in and out of DOM.
n - tr
o
an
This attribute is defined in the HTML5 specification: http://www.w3.org/TR/DOM-
s
) h a deฺ
Parsing/#extensions-to-the-element-interface.
ฺrs t Gui
2. document.write(): This method writes a string of text to a document stream. It
s
parameter replaces
p p
em uden
causes the document to be replaced in-place; this means that the string that is sent as a
@
the current content in the document.
a n S t
s
uk e thi s
This method is part of the DOM Level 2 HTML specification at
ฺ v
an
http://www.w3.org/TR/DOM-Level-2-HTML/.
s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 36


Example: DOM Manipulation

Use the JSConsole web application and run the following


example to see how to manipulate DOM elements.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 5 minutes

n s e
ice
b l el
er a
Tryathisn sf section
sectio
t r
-JSConsole.
n oin
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Click the buttons on the Preview tab to see how elements are added, removed or duplicated.
u
V
i l anThe code in JSConsole is the same as in the slides. You can refer to the slides at any time
M while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 4 - 37


Where Can I Learn More?

Resource Website
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

HTML5 W3C Specification http://www.w3.org/TR/html5/

W3C Document Object


h //
http://www.w3.org/DOM/
3 /DOM/
Model

Live DOM Viewer http://software.hixie.ch/utilities/js/live-dom-viewer/


n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 38


Summary

In this lesson, you should have learned how to:


• Create HTML5 documents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Create HTML5 forms to request information and process it


• Validate HTML5 forms input
• Write JavaScript functions for HTML5 events
• Manipulate HTML5 elements through DOM
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 39


Practice 4: Overview

This practice covers the following topic:


• 4.1: Writing JavaScript Code to Modify Document Elements
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 4 - 40


5
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

The JavaScript API ice n s e


b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
s an Day

) h a deฺ
s ฺrs t Gui Hands-On Practice

@ em uden Lecture

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 2


Objectives

After completing this lesson, you should be able to:


• Validate user input with JavaScript and regular expressions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Handle multiple values with JavaScript collections


• Manipulate dates with the JavaScript date API

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 3


Topics

• Parsing and validating


• URL Encoding
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Strings
• Dates
• Regular expression object
• JavaScript arrays and collections
n s e
• Objects ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 4


Topics

• Parsing and validating


• URL Encoding
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Strings
• Dates
• Regular expression object
• JavaScript arrays and collections
n s e
• Objects ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 5


The JavaScript API

JavaScript contains a set of functions and objects, which you can


use to perform a number of tasks, including:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Converting text to numbers


• Checking types such as NaN and Infinity
• Manipulating text data
• Validating input
n s e
• Creating collections of data
e l ice
• Accessing the browser window, parent document, and a l
bso
e r
on nsf a
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 5 - 6


Parsing Numbers

Scenario: You want to know how many years the user has left
until he is 100 years old.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<div>
Years until you are 100 years old:
<input type="text" id="ageInput"/>
<input type="button" value="calculate" id="ageButton"/>
n s e
ce
<div id="ageOutput">&nbsp;</div>
</div>
el i
a b l
fe r
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks you can convert numbers to strings and parse strings to numbers.
In JavaScript
u
V input is always in the form of strings. The values inside input fields are treated as
nHTML
a strings always. If you want to use numbers instead, you must parse the data from the HTML
Mil
forms.
To parse data, you have the parseInt and parseFloat methods.
When applying arithmetic operations on strings and numbers, the results are different
depending on the data type. For instance:
2+2 = 4
Whereas
"2"+"2" = "22"
And string has precedence when adding:
"2"+2="22"
Be careful because this is not always true for other operations:
"2"/2 = 1
To prevent bugs in your code, if you are going to use numbers, parse them before handling
them.

JavaScript and HTML5: Develop Web Applications 5 - 7


Adding Events to DOM

window.addEventListener("load", function() {…}, false);


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var button = document.getElementById("ageButton");


button.addEventListener("click", function() {…}, false);

n s e
ice
window.addEventListener("load", function() {
b l el
var button = document.getElementById("ageButton");
fe r a
b
button.addEventListener("click",
dd i ( li k function()
f i () {
a n s
// Button click logic goes here n - tr
o
an
}, false); // closes the button event handler
s
) h a deฺ
}, false); // closes the window event handler

s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks in the slide, you add the basic listeners to the page by using JavaScript.
In the example
u
Vwindow listener is used in this example because you want to execute the function after
l a n
The
Mi the page has finished rendering and you have access to all the DOM elements.
The button click listener executes the function when the user clicks the button.
Finally the third block shows both listeners in use.

JavaScript and HTML5: Develop Web Applications 5 - 8


Number Parsing and Output
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var ageOutputElement = document.getElementById("ageOutput");


var ageTextElement = document.getElementById("ageInput");

var ageTextValue = ageTextElement.value;


g = p
var age parseInt(ageTextValue,
( g , 10);
);

var result = "";

if (isNaN(age)) { n s e
ice
result = "Input a number please.";
b l el
ageTextElement.value = "";
} else { fe r a
a n s
result = ((100 - age) + " years before you turn 100!");
n - tr
}
o
console.log(result);
s an
ageOutputElement.innerHTML = result;
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksnumbers, you use the parseInt(string, radix) function.
To parse
u
nYouV can parse a string in any radix by using the radix argument. Omitting this argument
a defaults the argument to 10. As a result, you will get a number or a NaN (Not a Number)
Mil value. Remember that numbers in JavaScript can have any numerical value: NaN, Infinity,
and –Infinity.
If you provide an invalid string, the result of parseInt will be NaN.
You can check if a number is NaN by using the isNaN function.

JavaScript and HTML5: Develop Web Applications 5 - 9


Tip Calculator

Scenario: You and some friends go for lunch and opt to divide
the bill, adding a 10% tip.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<div>
Tip Calculator<br>
<input type="text" id="tipTotalBill"/>
<input type="text" id="tipNumberOfPeople"/>
<input type="button" value="calculate" id="tipButton"/>
n s e
ice
el
<div id="tipOutput">&nbsp;</div>
</div>
a b l
fe r
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k a
s with floating point numbers instead of integers, you use the
If you deal
V u
parseFloat(string) function.
l a n
Mi Remember that all inputs from HTML forms return their values as strings in JavaScript.

JavaScript and HTML5: Develop Web Applications 5 - 10


Tip Calculator Logic
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var billTotal = parseFloat(tipTotalBillElem.value);


var people = parseFloat(tipNumberOfPeopleElem.value);
//add the tip
var totalWithTip = billTotal + (billTotal * 0.1);
0 1);
//divide the total
var dividedTotal = totalWithTip / people;
if (isNaN(dividedTotal)) {
n s e
ce
tipOutputElem.innerHTML = "Please input numbers.";
} else if (isFinite(dividedTotal)) {
el i
tipOutputElem.innerHTML = "Each of you will pay:"+dividedTotal; a b l
fe r
} else {
a n s
tipOutputElem.innerHTML = "Can't divide by 0.";
n - tr
} o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksfractional numbers, use the parseFloat(string) function.
To parse
u
nToVcheck whether a number is infinity or –infinity, use the isFinite(number)
a function.
Mil
This is specially useful when doing divisions.
5 / 0 = infinity
-5 / 0 = -infinity
0 / 0 = NaN

JavaScript and HTML5: Develop Web Applications 5 - 11


Number.toLocaleString()

Use toLocaleString() in numbers to get a string


representation of a number for display.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Usage:
number.toLocaleString(Locale, Options)
Locale is a string representing the BCP 47 language tag (for
example, “en-us”).
Options is a JavaScript object that provides specific parameters ense
ic
that are used to display the number. le l b
f e ra
n s
number.toLocaleString("en-US", { n - tra
o
an
style: "currency", currency:s "USD",
) h a deฺ
s
maximumFractionDigits: ฺr2}); ui
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
You can a
ksuse toLocaleString to convert numbers to strings with added localization
V u
information.
l a n
Mi In the example in the slide, the number is displayed as a currency value.
Given the number=15.2532, the string representation will be: "$12.25".
Although this method seems useful, it is not as widely used because the output is dependent
on the browser and the user’s locale settings.

JavaScript and HTML5: Develop Web Applications 5 - 12


Intl.NumberFormat

To reuse formatting settings, you can use the


Intl.NumberFormat object:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var numberFormat = new Intl.NumberFormat("en-


US", { style:
l "currency",
currency: "USD",
maximumFractionDigits: 2}); n s e
lice
var string1 = numberFormat.format(number1); ble
f e ra
ns
var string2 = numberFormat.format(number2);
a
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The entire API for localizing strings is located inside the Intl.NumberFormat object. You
u
V
can create the format objects and use them with the numeric values in your application.
an
Mil In addition to Intl.NumberFormat, you have Intl.DateTimeFormat for formatting
dates.
As discussed in the previous slides, this method is not recommended because the output
might vary from browser to browser.
You can find more information about localization in: https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Intl.

JavaScript and HTML5: Develop Web Applications 5 - 13


HTML5 Number Input and JavaScript

As a safety measure and to ensure compatibility, always parse


values by using JavaScript.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<input type="number" id="numberInput">

Parse by using:
n s e
lice
var elem = document.getElementById("numberInput");
a b le
r
var number = parseInt(elem.value); sfe n
n - tra
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Always parse values even if you use the HTML5 number input. The HTML input elements
u
V
store their values as strings.
an
Mil

JavaScript and HTML5: Develop Web Applications 5 - 14


Example: Parsing Numbers

Use the JSConsole web application and run the following


example to see how to parse values from HTML pages.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
o n -tr
Try this in
s an
JSConsole.
) h a deฺ
s ฺrs t GuiJavaScript Parsing Numbers
@ em uden Parse and validate numbers.

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example in the slide. You can view or edit the example to
u
Vsome of the JavaScript code discussed in this section.
see
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 5 - 15


Topics

• Parsing and Validating


• URL Encoding
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Strings
• Dates
• Regular expression object
• JavaScript arrays and collections
n s e
• Objects ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 16


Decoding and Encoding URI

Scenario: You construct a URI by using JavaScript, but it


contains special characters such as spaces or symbols.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

You also need to decode URI with spaces and symbols to get the
parameters that the URI has.
var uri = "http://www.oracle.com/list?order:by name";

var encodedUri = encodeURI(uri);


n s e
console.log(encodedUri);
ice
//http://www.oracle.com/list?order:by%20name
b l el
fe r a
var decodedUri
i = decodeURI(encodedUri);
( i) a n s
console.log(decodedUri);
o n -tr
n
//http://www.oracle.com/list?order:bya name
h a s eฺ
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Uniform a
ksResource Identifiers (URIs) cannot contain special characters. Instead of using these
V u
characters directly, you need to escape them. The process of escaping all special characters
l a n
Mi is known as encoding.
If you are going to use URIs in your application, encode them before sending it to the browser
or making requests. If you need to parse information in the form of URIs, decode them before
using them.
In the example in the slide, note how spaces are replaced by %20, which is the escape code
for a space.

JavaScript and HTML5: Develop Web Applications 5 - 17


Example: URL Encoding

Use the JSConsole web application and run the following


example to see how to encode and decode URLs.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
o n -tr
Try this in
s an
JSConsole.
) h a deฺ
s ฺrs t GuiJavaScript URI
@ em uden Encode and decode URIs.

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example in the slide. You can view or edit the example to
u
Vsome of the JavaScript code discussed in this section.
see
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 5 - 18


Topics

• Parsing and Validating


• URL Encoding
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Strings
• Dates
• Regular expression object
• JavaScript arrays and collections
n s e
• Objects ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 19


String Creation

• var s = "this is a string"


• var s = new String("this is a string")
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Escape sequences: \' \" \\ … and so on

• What about international characters?


s e
var s = "中文 español English िह दी ‫اﻟﻌﺮﺑﻴﺔ‬ lice n
português বাংলা русский 日本語 ਪੰ ਜਾਬੀ 한국어" ble
f e ra
• Use Unicode: a ns
var s = "\u4E2D" = "中" o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
To create strings, you can use the Code Output
V
literal value with simple or double
an
Mil quotation marks. Single quote
\’
For instance: \" Double quote
String s = "hello"; \\ Backslash
is the same as:
\n new line
String s = 'hello';
\r Carriage return
If you decide to use double quotation
marks to enclose your strings
strings, you \t T b
Tab
need to escape all double quotation
marks. \b Backspace
The table on the right contains some \f Form feed
string escape notations: \u… Unicode codepoint

JavaScript and HTML5: Develop Web Applications 5 - 20


String Manipulation

One of the most common operations that you perform is string


manipulation:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Concatenation: "hello "+"world" = "hello world";


• CharAt: "hello world".charAt(4) = 'o'
• indexOf: "hello world".indexOf("world") = 6
"hello world".indexOf("no") = -1
• replace: "hello world".replace("world", "John") = "hello n s e
ice
el
John"
a b l
• split: "hello world".split(" ") = ["hello","world"]
er
ns f
t r a
no n-
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The slide shows some string manipulation methods and the result of invoking such methods
u
V
on the "hello world" string.
an
Mil • To concatenate strings,g , you
y can use the + operator.
p
• charAt returns the character in the given index.
• indexOf returns the index of the first occurrence of the matched string or -1 if the
string is not found.
• replace replaces all occurrences of a string with another, if found.
• split returns an array with strings that result from splitting the original string by using
the pprovided separator.
p

JavaScript and HTML5: Develop Web Applications 5 - 21


String Manipulation

• substring: "hello world".substr(3) = "o world"


• toLowerCase: "Hello World".toLowerCase() = "hello
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

world"
• toUpperCase: "Hello World".toUpperCase() = "HELLO WORLD"
• trim:
ti " Hello World ".trim() = "Hello World"

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
The slide a
sshows some string manipulation methods and the result of invoking such methods
onV u
the "hello world" string.
l a n
Mi • substringg returns the stringg from the start,, at a ggiven index.
• toLowerCase returns the string with all the letters in lowercase.
• toUpperCase returns the string with all the letters in uppercase.
• trim removes trailing and leading spaces and tabs from the string.

JavaScript and HTML5: Develop Web Applications 5 - 22


Validating and Parsing String Values

Scenario: Data is provided to you in comma-separated values


and you must display it in your application.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var data = "John,Doe,32,1982,10,23,153.25, A ,";

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
There k
are a
s better ways to store information than on a spreadsheet and information can be sent
byV u
using any other format than comma-separated strings such as XML or JSON, but that is
l a n
Mi covered in the next lesson titled “Application Data.”

JavaScript and HTML5: Develop Web Applications 5 - 23


Splitting the String

Splitting the text creates an array of strings:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var data = "John,Doe,32,1982,10,23,153.25, A ,";

var splitData = data.split(",");

console.log(splitData[0]); // "John"
n s e
console.log(splitData[1]); // "Doe"
lice
console.log(splitData[2]); // "32"
a b le
console.log(splitData[3]); // "1982"
s f er
console.log(splitData[4]); // "10"
- t r an
console.log(splitData[5]); // "23"
n o n
console.log(splitData[6]); // a
"153.25"
console.log(splitData[7]); // "haAs " eฺ
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Using the split method, you can separate data from a string.
u
V
an
Mil

JavaScript and HTML5: Develop Web Applications 5 - 24


Topics

• Parsing and validating


• URL encoding
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Strings
• Dates
• Regular expression object
• JavaScript arrays and collections
n s e
• Objects ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 25


JavaScript Dates

JavaScript provides a Date object for handling dates:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

new Date();
// Creates a new date with the current date and time.

new Date(value);
// Value must be a numeric integer value representing the
// number of milliseconds since January 1st 1970 00:00:00 UTC. n s e
ice
new Date(dateString); b l el
// dateString must be a string in IETF-compliant RFC 2822 fe r a
a n s
-tr
// timestamp or ISO8601 format.

n o n
new Date(year, month, day, hour, minute, a second,millisecond);
// A set of integers representing each
h a s
value
e ฺ the date.
for
d
s ฺrs) t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ksJavaScript object lets you create and manipulate dates.
The Date
u
V can create dates in different ways. The slide shows how to create dates by using the
l a n
You
Mi different constructors.

JavaScript and HTML5: Develop Web Applications 5 - 26


Date String Examples

You can create dates with the following string formats:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

// RFC 2822
"Aug 9, 1985"
"Wed, 09 Aug 2014 00:00:00 GMT"
"Wed, 09 Aug 1995 00:00:00"
n s e
ce
"01 Jan 2011 00:00:00 GMT-0400"
el i
a b l
// ISO 8601
fe r
a n s
"2011-05-22"
n - tr
o
"2011-05-22T14:48:00"
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks dates by using strings, you have two different ways to represent dates in strings.
To create
u
an •V Using the RFC 2822: More information at http://tools.ietf.org/html/rfc2822#page-14
Mil • Using ISO 8601: More information at
http://www.iso.org/iso/home/standards/iso8601.htm

JavaScript and HTML5: Develop Web Applications 5 - 27


Date Object

Create Date objects to manipulate dates.


Using dates, you have methods to get and set specific fields in a
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

date.

Date date = new Date("2011-05-22T14:48:00")


Console.log(date.getDate());
// It will return 22 which is the day of the month. n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks methods for dates are:
The getter
V u
i l a n
date.getDate() // Number (1-31)
M date.getFullYear()
date getFullYear() // Number (4 digit year)
date.getHours () // Number (0 to 23)
date.getMilliseconds() // Number (0 to 999
date.getMinutes() // Number (0 to 59)
date.getMonth() // Number (0 to 11)
g
date.getSeconds() // Number (0 to 59)
date.getDay() // Number (0=Sunday to 6= Saturday)
date.getTime() // Number (Milliseconds since Jan 1st 1970)

JavaScript and HTML5: Develop Web Applications 5 - 28


Modifying a Date

Use Date.setTime(timestamp);.
The time stamp is the number of milliseconds since January 1st
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

1970 00:00:00 UTC.

Alternatively, you can use the set methods in a date:

n s e
date.setDate(14);
lice
// sets the day of the month to 14. All other a b le
s f er
// fields (month
(month, year n
year, etc)remains unchanged
unchanged.
a
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The following are the setter methods for date:
u
V
an
date.setDate([number 1 to 31]);
Mil date setFullYear([4 digit number]);
date.setFullYear([4
date.setHours([number 0 to 23])
date.setMilliseconds([Number 0 to 999])
date.setMinutes([Number 0 to 59])
date.setMonth([Number 0 to 11])
date.setSeconds([Number 0 to 59])
date.setDay([Number 0=Sunday to 6= Saturday])
date.setTime([Number Milliseconds since Jan 1st 1970])

JavaScript and HTML5: Develop Web Applications 5 - 29


Date Operations

Given:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var startDate = new Date();


//Some complex code..
var endDate = new Date();

To calculate the elapsed time between two dates in milliseconds:


n s e
var elapsed = endDate – startDate;
ice
Is the same as: b l el
er a
var elapsed = endDate.getTime() nsf
endDate getTime() – startDate.getTime();
startDate getTime();
a
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
One of the most common operations used in dates is the subtraction of their millisecond
u
V
values to get the time elapsed between two dates.
anIn fact, directly subtracting two dates results in the same value as subtracting the millisecond
Mil
values of each date.
You can output the value of a date by using the toString() or toLocaleString()
methods. The result of invoking these methods is client dependent. If you want control over
how dates are presented, use the individual get methods.
Date values are dependent on the client’s time configuration. Do not assume that the time and
date from Date objects are universal and in sync. Date objects should be treated as relative to
the client machine.

JavaScript and HTML5: Develop Web Applications 5 - 30


Example: JavaScript Dates

Use the JSConsole web application and run the following


example to see how to handle date objects in JavaScript.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
o n -tr
Try this in
s an
JSConsole.
) h a deฺ
s ฺrs t GuiJavaScript Parsing Dates
@ em uden Parse and validate dates.

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example in the slide. You can view or edit the example to
u
Vsome of the JavaScript code discussed in this section.
see
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 5 - 31


Reading and Parsing Dates

Scenario: A user inputs his or her birth date and you want to tell
the user how many hours are left before his or her next birthday.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var nextBirthDay = new Date();


nextBirthDay.setDate(parseInt(dayElement.value));
nextBirthDay.setMonth(parseInt(monthElement.value)-1);
tBi thD tM th( I t( thEl t l ) 1)
nextBirthDay.setHours(0);
nextBirthDay.setMinutes(0);
if (nextBirthDay.getTime() < Date.now()) { n s e
//It is on next year.
e l ice
nextBirthDay.setFullYear(nextBirthDay.getFullYear()+1);
r a bl
}
n s fe
a
var milliseconds = nextBirthDay.getTime() --trDate.now();
n
no * 60 * 60));
var hours = Math.round(milliseconds / (1000
var days = Math.round(hours / 24); s a
) h adaysd+eฺ" days) left
i
sฺrs t Gu
var result = hours + " hours (" +
before birthday!";
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The code in the slide demonstrates how to create Date objects and use parsed information to
u
V
modify and set a specific date.
an
Mil

JavaScript and HTML5: Develop Web Applications 5 - 32


Exercise: JavaScript String Manipulation

Use the JSConsole web application and try to solve the exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Parse a string and generate a JS object.

Time Limit: 15 minutes

n s e
ice
b l el
fe r a
a n s
o n -tr
s an
) h a deฺ
s G ui JavaScript String Parsing
ฺrs Exercise:
e m dent Parse strings to get data.

a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks browser, go to the JSConsole application, and run the exercise.
Open your
u
V the required JavaScript code to make the tests pass.
l a n
Add
Mi You can find more help on how to solve a particular test by clicking the result
result.

JavaScript and HTML5: Develop Web Applications 5 - 33


Solution: JavaScript String Manipulation

var data = "John,Doe,32,1982,10,23,153.25, A ,";


var person = {};
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var splitData = data.split(",");


person.firstName = splitData[0];
person.lastName = splitData[1];
p p
person.age = parseInt(splitData[2]);
person.credit = parseFloat(splitData[6]);
person.rating = splitData[7].trim(); n s e
var year = parseInt(splitData[3]); e l ice
r a bl
var month = parseInt(splitData[4])-1;
n s fe
var day = parseInt(splitData[5]);
n - tra
o 0, 0, 0, 0);
person.birthdate = new Date(year, month, day,
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 5 - 34


Topics

• Parsing and validating


• URL encoding
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Strings
• Dates
• Regular expression object
• JavaScript arrays and collections
n s e
• Objects ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 35


Regular Expressions

You can use regular expressions to search for patterns on strings.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Regular expressions are independent JavaScript objects:

var regex = new RegExp(pattern [, flags]);

n s e
Alternatively, you can use the Regex literal: ice
b l el
fe r a
var regex = /pattern/flags
/ tt /fl a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks regular expression objects in JavaScript allow you to match strings and perform
• The
u
V parsing, replace, and search operations.
an •
Mil Regular
egu a eexpressions
p ess o s a
are
e co
commono in ot
other
e languages;
a guages; in Ja JavaScript,
aSc pt, you can
ca use tthe
RegExp constructor or the regular expression literal to construct regex objects.
e

• Regular expressions in JavaScript use the standard notation for regexp patterns.
For more information about regular expressions, go to: http://www.regular-
expressions.info/javascript.html.

JavaScript and HTML5: Develop Web Applications 5 - 36


Sample Regular Expression

var regexp = /oracle/i


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Pattern Flags

Matches: s e
ce n
el i
a b l
"Visit oracle.com for more information"
fe r
a n s
o n -tr
"ORACLE PRODUCTS"
s an
) h a deฺ
s ฺ rs t Gui
"Oracle provides courses e m din e n Oracle University"
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ksexpression will search for matches in strings.
A regular
u
anTheVtext inside “/” can be any string or one or many character classes.
Mil You can add flags to the entire regular expression.
expression The available flags are:
• g: Global match
• i: Ignore case
• m: Multiline, which is used to define a regular expression that might extend over many
lines that are separated by \n or \r. Special character classes take effect on multiple
lines.
• y: Sticky,
Sticky which is used to match only from the index that is indicated by the lastIndex
property of the regular expression
/oracle/i
In the preceding example, the regular expression will search for the first occurrence of the text
“oracle,” ignoring the upper and lower cases (i flag).
/oracle/gimy
IIn the
h preceding
di example, l the
h regular
l expression i will
ill search
h ffor the
h text ““oracle,”” ignoring
i i
the lower or uppercase (i flag) in the entire string (g flag) and treating new lines inside the
search patterns (m flag) from a specific point defined by the lastIndex property of regexp
(y flag).
JavaScript and HTML5: Develop Web Applications 5 - 37
Sample Regular Expression

var regexp = /[a-z]*/


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Pattern: All lowercase letters

Matches: s e
ce n
el i
a b l
"Visit oracle.com for more information"
fe r
a n s
o n -tr
"ORACLE PRODUCTS"
s an
) h a deฺ
s ฺ rs t Gui
"Oracle provides courses e m din e n Oracle University"
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ksuse patterns (character classes) inside the regular expression text.
You can
V u
i l a n
Character classes define flexible matchers that can be used to match any type of text.
M • [a-z]
[a z] matches a single lowercase letter
letter.
• [A-Z] matches a single uppercase letter.
• [abc] matches the letter a, b, or c.
You can add quantifiers to specify how many times a character class is to be matched.
• [a-z]* matches zero or multiple lowercase letters.
• [a-z]+ matches one or multiple lowercase letters.
• [aA]+[a-zA-Z]* matches all words that start with at least one “A” or “a.”
You can find more information about the character classes in JavaScript at:
http://www.regular-expressions.info/javascript.html.

JavaScript and HTML5: Develop Web Applications 5 - 38


Submatched Parentheses Expressions

var regexp = /(o+)r/i


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Pattern: One or more O’s followed by an r


Submatch: One or more O’s at the beginning of the pattern

Will match: s e
ce n
el i
a b l
"Visit oracle.com for more information"
fe r
a n s
o n -tr
"ORACLE PRODUCTS"
s an
) h a deฺ
s ฺ rs t Gui
"Oracle provides courses e m din e n Oracle University"
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
Using k s a
parentheses in a regular expression executes a subsearch inside the matched
V u
expression for every parenthesized pattern.
l a n
Mi In the example in the slide, the regular expression:
1. Matches the expression o+r: any number of o’s followed by an r
2. Makes a subsearch of o+: any number of o’s from the matched result
3. Saves each submatch

JavaScript and HTML5: Develop Web Applications 5 - 39


Regular Expression Methods

• exec([String]):Object
Executes a search in the string for the pattern, returns an
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

object with information about the search, and updates the


regexp object

• test([String]):Boolean
Returns true if the string contains one or more matches of s e
the search pattern ce n
el i
a b l
fe r
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks method returns a result object with the following properties:
The exec()
u
•V result[0] = The last matched characters
l a n
Mi • result[1] to result[n] = The saved substring matches matches, if any
any, that were defined by
using parenthesized patterns
• result.index = The index of the match in the string
• result.input = The input string
Additionally, the regexp object is updated with the following properties:
• Regexp.lastIndex = The index to start the next match
The ffollowing
Th ll i code
d allows
ll you to execute consecutive
i searches
h over a single
i l string:
i
while ((result = regexp.exec(string)) !== null) {
console.log("Match Found: " + result[0]);
}

JavaScript and HTML5: Develop Web Applications 5 - 40


String RegExp Methods

regexp objects can be used in the following string methods:


• String.replace(regexp, newString)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Replaces all the matched instances of the pattern with the


new string
• String.match(regexp)
i h( )
Returns an array of strings with all the matched patterns
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
The String.replace method can receive both a string or a regular expression as its first
V u
parameter.
l a n
Mi Given var string = "my my mind";
mind ;
• string.replace("my","your"); // "your mind"
• string.replace(/my/, "your"); // "your mind"
Both invocations will replace "my" with "your" but the second invocation will do it by using
regular expressions.
• string.replace("my*", "your"); // "my mind"
This replaces the string my*
* with "your"
" " but there are no instances of my*.
*
• string.replace(/my*/, "your"); // "your yourind"
This replaces every match that begins with m and is followed by any number of y’s (even
none) with "your".

JavaScript and HTML5: Develop Web Applications 5 - 41


RegExp Example

Scenario: You want to validate the email address provided by the


user.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

A simple
p p pattern to match emails is:

[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}
n s e
li ce
Matches email names @ Host names b
dot 2 to 4 characters l e
e r a
com,sfco, jp
- t r an
n on
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
an(
ks
The <input type="email"> HTML5 input type can also be used but sometimes it is not
u
V
available in legacy code.
anRegular expressions are usually language independent. You can search for regular
Mil
expressions on the net if you need to match a particular pattern.
The example in the slide uses a simplified regular expression for emails but you can construct
a more complete one by using the RFC5322 section 3.4 email address specification.

JavaScript and HTML5: Develop Web Applications 5 - 42


Example: JavaScript Regular Expressions

Use the JSConsole web application and run the following


example to see how to validate emails by using regexp.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
o n -tr
Try this in
s an
JSConsole.
) h a deฺ
s G ui Regular Expressions
ฺrs tJavaScript
@ em uden Validate emails with regex.

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example in the slide. You can view or edit the example to
u
Vsome of the JavaScript code discussed in this section.
see
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 5 - 43


Topics

• Parsing and validating


• URL encoding
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Strings
• Dates
• Regular expression object
• JavaScript arrays and collections
n s e
• Objects ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 44


JavaScript Arrays as Collections

To modify arrays and treat them as collections, you can use


several methods:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• array.pop() removes and returns the last element of the


array.
• array.push(value)
h( l ) adds dd th
the value
l att th
the end d off the
th array.
• array.shift() removes and returns the first element of the
array. n s e
• array.unshift(value) adds the value at the start of the e l ice
array. r a bl
n s fe
• array.splice() removes and replaces items.
n - tra
• array.indexOf(value) gets the index a noof value.
• array.join() joins all items s
as dstring.
in) ahsingle eฺ
u
ฺr t Gi
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
JavaScript arrays contains multiple methods that let you manipulate them.
u
V
i l anTo use these methods, create an array and call the method on the array.
M var names = ["edward"
["edward", "john",
"john" "steve"];
names.push("peter")

JavaScript and HTML5: Develop Web Applications 5 - 45


Array Methods

• pop:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var shapes = ["triangle", "circle", "square"];


var shape = shapes.pop();
shape; // "square"
shapes; // ["triangle", "circle"]

n s e
ice
• push: b l el
fe r a
a n s
var months = ["Jan", "Feb", "Mar"]; n -t r
o
months.push("Apr","May","Jun");
s an
months; ha"Apr",eฺ "May", "Jun"]
// ["Jan", "Feb", "Mar",
s ) id
ฺ r u
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n(

u ksa Removes and returns the element at the end of the array
pop:
V push: adds elements at the end of the array and returns the length of the array

an
Mil

JavaScript and HTML5: Develop Web Applications 5 - 46


Array Methods

• shift:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var shapes = ["triangle", "circle", "square"];


var shape = shapes.shift();
shape; // "triangle"
shapes; // ["circle", "square"]

n s e
ice
• unshift: b l el
fe r a
a n s
o n -tr
var elements = ["fire", "water", "earth", "air"];

a n "water",
elements.unshift("fifth element");
elements; s
// ["fifth element", "fire",

) ha ide
"earth", "air"]
ฺrs t Gu
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n(

u ksa Is similar to the pop method. It removes and returns the removed element of the
shift:
V array, but in this case, at the beginning of the array.
an •
Mil unshift: Adds one or more elements at the beginning
of the array.
g g of the array.
y It returns the length
g

JavaScript and HTML5: Develop Web Applications 5 - 47


Array.Splice()

Splice is used to add and remove elements at a certain index.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

array.splice(index, removeCount, element1,


element2, … elementN);

Splice removes the removeCount elements from the array at the


specified index, and then adds all the other elements in place of ense
ic
the removed ones (if any). le l b
f e ra
n s
n - tra
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Common uses of splice:
u
V
• Removes an element at an index: array.splice(index, 1);
an
Mil • Adds an element at an index: array.splice(index,
array splice(index 0 0, element);
• Replaces an element: array.splice(index, 1, element); or array[index]
= element;
• Removes all elements after an index: array.splice(index, array.length-
index);

JavaScript and HTML5: Develop Web Applications 5 - 48


Array.join()

Use Array.join to create a string representation of the array


contents.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

[1,2,3,4].join(", "); // "1, 2, 3, 4"

["a","b","c"].join("-"); // "a-b-c"
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Use array.join(separator) to generate a string representation of the array, separated
byV u
the provided separator.
l a n
Mi This is particularly useful to convert the array to a string for later display.

JavaScript and HTML5: Develop Web Applications 5 - 49


Array.indexOf()

• indexOf:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var items = ["pencil", "scissors", "eraser", "tape"];


var index = items.indexOf("eraser");
index; // 2
index = items.indexOf("glue");
index; // -1
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks The indexOf method returns the index of the first element that is found in the
indexOf:
u
V that matches the value sent as a parameter.
array
l a n
Mi Similar to this method, lastIndexOf also searches for index occurrences but it returns the
last index that is found.
More information about Array methods can be found at https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods.

JavaScript and HTML5: Develop Web Applications 5 - 50


Reading and Parsing HTML Lists with JS Arrays

Scenario: The user selects elements from a list and you want to
display the elements that the user selected.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var listElement =
document.getElementById("listElement");
var result = [];
for(var i = 0; i<listElement.length;i++){
if(listElement[i].selected){
n s e
result.push(listElement[i].value);
ice
}
b l el
}
fe r a
console.log(result.join(",
l l ( lt j i (" "))
"));
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k s a
In the example, you read the contents of a list input in HTML5 and store the user selection in
V u
a JavaScript Array by using the push method. Then the array is displayed in the console by
l a n
Mi using the join method.

JavaScript and HTML5: Develop Web Applications 5 - 51


Example: JavaScript Arrays

Use the JSConsole web application and run the following


example to see how to use array methods.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s G ui Arrays
ฺrs tJavaScript
@ em uden Use arrays as collections.

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example in the slide. You can view or edit the example to
u
Vsome of the JavaScript code discussed in this section.
see
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 5 - 52


Exercise: JavaScript String Manipulation

Use the JSConsole web application and try to solve the exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Use JavaScript array methods to pass the tests.

Time Limit: 15 minutes

n s e
ice
b l el
fe r a
a n s
o n -tr
s an
) h a deฺ
s G ui JavaScript Arrays
ฺrs Exercise:
e m dent Use array operations

a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks browser, go to the JSConsole application, and run the exercise.
Open your
u
V the required JavaScript code to make the tests pass.
l a n
Add
Mi You can find more help on how to solve a particular test by clicking the result
result.

JavaScript and HTML5: Develop Web Applications 5 - 53


Solution: JavaScript Arrays

//Add the following:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

animals.pop();
animals.pop();
numbers.push(10);
floats.splice(2,1);
colors.splice(3,1,"orange");
n s e
people=[];
lice
// people.splice(0,people.length); a b le
s f er
// people.length=0;
l l th 0
- t r an
n on
// while(people.length>0){people.pop();}
s a
h a
functions.push(function(){return eฺ
true;});
) id
ฺ r s u
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 5 - 54


Topics

• Parsing and validating


• URL encoding
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Strings
• Dates
• Regular expression object
• JavaScript arrays and collections
n s e
• Objects ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 55


JavaScript Objects

Objects creation (refresher)


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Inline direct instance (singleton): Class function declaration:

var object = { function className(){


property1:value, this.property1=value1;
method:function(){}, this.method=function(){};
property2: value}; this.property2=value2;
} n s e
or li ce
b l e
var object = new className();
e r a
var object = new
a n sf
function(){ -tr
// className.prototype
o n
this.property1=value1;
s an
this.method=function(){};
) h a deฺ
this.property2=value2;
s ฺ r s Gui
}
e m dent
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ksare usually created in two ways: by using the direct instance or by using a function as
Objects
V u
na constructor.
a The slide shows the two different ways of creating objects.
Mil
Using the inline syntax with curly braces ({}) is also called an object literal.
The main difference between the two ways of creating objects is that using literals, JavaScript
creates a different object every time and it is difficult to reuse code. Each object that is created
with literals will have its prototype initialized to the default object.
Using constructors, each object that is created will have a new prototype that is accessible by
using
us gc ass a e.p ototype, which
className.prototype, c isssshared
a ed for
o a
all instances.
sta ces

JavaScript and HTML5: Develop Web Applications 5 - 56


Static Object Methods

• Some static methods of the Object constructor:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

- Object.create()
- Object.defineProperty()
- Object.getOwnPropertyDescriptor()
- Object.getOwnPropertyNames()
- Object.getPrototypeOf()
n s e
ice
b l el
f er a
var obj
j = { a : 45 }
};
Object.defineProperty(obj, "double_a", {get t:ran
s
function(){ return this.a * 2; }}); non
-
s
Object.defineProperty(obj, "modify_a",a {set :
a ฺ
)h
function(x){ this.a -= x; }}); ide
ฺrs t Gu
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Methods are also available in the Object constructor. These methods are static, which
u
V
means that there is no need to instantiate an object to use it. You have already seen one of
an
Mil these methods, which is Object.create(), which is used to create a new object.
Other methods work with property attributes, such as Object.defineProperty(), which
defines a new property on an object, and can be used to define its get and set methods as
well, just as you did when you initialized an object in the topic titled “Accessing Objects
Properties” in the lesson titled “JavaScript Fundamentals.” The example in the slide shows an
alternative of what was shown earlier with the get and set methods.
• Object.getOwnPropertyDescriptor returns a property descriptor for an own
property In the example,
property. example if this method is called as the following:
Object.getOwnPropertyDescriptor(obj,"double_a"); the result is:
Object {get: function, set: undefined, enumerable: false, configurable: false}.
• Object.getOwnPropertyNames returns an array of strings with the own properties of
an object. In the example, the result is: ["a", "double_a", "modify_a"].
• Object.getPrototypeOf returns the prototype of the specified object.
More information about Object methods can be found at https://developer.mozilla.org/en
https://developer mozilla org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Object#Methods.

JavaScript and HTML5: Develop Web Applications 5 - 57


Prototypes

All JavaScript objects have a prototype property.


Methods and “static” values are usually declared in the prototype.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

A class function declaration by using a prototype is as follows:

function className(){ n s e
ice
this.property1=value1;
b l el
this.property2=value2;
fe r a
}
a n s
o n -tr
an
className.prototype.method = function(){}
s
a deฺ
var object = new className();s) h
s ฺr t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks of the prototype is different for each constructor function you have.
The name
u
V object literals will set the prototype of these objects to the default object prototype.
l a n
Using
Mi

JavaScript and HTML5: Develop Web Applications 5 - 58


Object Methods

• Object methods inherited from Object.prototype:



Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

isPrototypeOf(obj)
– toLocaleString()
– toString()
– valueOf()
()

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Some k s a
methods are inherited from Object.prototype and they are available for all the
u
V that are created. You have already seen, for example, the hasOwnProperty method
objects
l a n
Mi to query whether a property is from the object and not from the prototype chain. Some other
inherited methods are:
• isPrototypeOf: Checks whether an object exists within another object’s prototype
chain
• toString: Returns a string representation of the object
• toLocaleString: Returns a string representation of the object but sensitive to the
host environment’s current locale
• valueOf: Returns the primitive value of the specified object. The result of calling this
function in myObj from the example in the slide is: Object {print: function}.
More information about Object.prototype methods can be found at
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype.

JavaScript and HTML5: Develop Web Applications 5 - 59


ToString Object Method

Overwrite the toString() method to provide an easy way to


represent objects as strings:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function Person(_name, _lastName) {


this.name = _name;
this.lastName = _lastName;
n s e
}
ice
b l el
Person.prototype.toString = function() {
f er a
return this.lastName
this lastName + ",
" " + this.name;
this name;
an s
}; n - t r
a no
var person = new Person("John","Doe");
h a s eฺ
console.log(person.toString());
ฺ r s u id John"
) // "Doe,
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
ks a
V u
an
Mil

JavaScript and HTML5: Develop Web Applications 5 - 60


Example: JavaScript Object Methods

Use the JSConsole web application and run the following


example to see how to use object methods.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s G ui Methods
ฺrs tObject
@ em uden Examples for Object Methods

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example in the slide. You can view or edit the example to
u
Vsome of the JavaScript code discussed in this section.
see
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 5 - 61


Where Can I Learn More?

Resource Website
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

JavaScript Standard built-in https://developer.mozilla.org/en-


objects US/docs/Web/JavaScript/Reference/Global_Objects

ECMA Script http://www.ecmascript.org/

Regular Expressions http://www.regular-expressions.info/


n s e
ice
Regex Tester http://regexpal.com/
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 62


Summary

In this lesson, you should have learned how to:


• Parse and validate user input from input elements by using
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

JavaScript
• Parse and manipulate dates
• Store multiple values and objects inside JavaScript arrays and
use them as collections
• Add and modify existing object methods by using prototypes n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 63


Practice 5: Overview

This practice covers the following topics:


• Practice 5-1: Creating a meal-divider application
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Practice 5-2: Calculating the total based on age

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 64


Assignment Overview

• This self-study assignment covers the following:


– Assignment 5-1
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Review the JavaScript built-in objects and methods


documentation and reference at
htt //d
https://developer.mozilla.org/en-
l ill /
US/docs/Web/JavaScript/Reference/Global_Objects.
• Research about the Document and Window Objects at n s e
lice
https://developer.mozilla.org/en-US/docs/Web/Reference/API.
e
– Go to the DOM interfaces section to find out more. r a bl
s fe
ntran
– Why do you think they are not part of ECMA script?
-
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 5 - 65


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Mil
an V u
ksa
n(
an ฺ v
mil to u
s
s
a n @
uk e thi s S t
s
)
em uden
h s
ฺrs t Gui
an
o
a deฺ
trn -
a n s fe
r
a b l el
i
ce n s e
6
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Web Application Data ice n s e


b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
s an Day

) h a deฺ
s ฺrs t Gui Hands-On Practice

@ em uden Lecture

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 2


Objectives

After completing this lesson, you should be able to:


• Convert objects to JSON strings
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Parse JSON strings into JavaScript objects


• Store objects by using the JSON API, cookies,
and local storage

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 3


Topics

• JSON Object Representation


– JSON Parsing
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– JSON Generation
• The JavaScript Sandbox
• Cookies
• Local Storage
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 4


Topics

• JSON Object Representation


– JSON Parsing
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– JSON Generation
• The JavaScript Sandbox
• Cookies
• Local Storage
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 5


JSON

JavaScript Object Notation is a simple format to represent


objects, arrays, and values as strings.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

JavaScript includes functions to convert objects, arrays, and


values
l tto JSON strings
ti and
d vice
i versa.

n s e
ice
b l el
fe r a
a n s
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden http://json.org/
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
The JavaScript Object Notation (JSON) is a format to represent JavaScript objects, arrays,
u
Vvalues as strings. It is one of the preferred ways of sending and receiving data from
and
l a n
Mi HTML applications.
JSON allows you to represent objects as key-pair values and arrays as sequential lists of
items.
Values can also be represented as JSON, allowing you to create all sorts of objects by using
strings, numbers, and Booleans.
JSON is often compared to XML because both can be used to represent structured data. The
main difference between JSON and XML is that JSON contains only data without any schema
information. Therefore, JSON has no direct validation mechanism.
Also JSON contains only string, number, and Boolean value types and Object and Array data
structures. You do not need to define custom data types or nodes as in XML. In JSON, data is
represented as it would be inside a JavaScript object, making it extremely flexible at the
exchange of validation and schema facilities.

JavaScript and HTML5: Develop Web Applications 6 - 6


JSON Strings

Arrays:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

[1,2,3]
["a","b","c"]

Objects:
{"name":"john","age":31}
n s e
{"itemId":["a","b"], "total":2, "active":true}le lice
ra b
s f e
tra values. n
• JSON is very similar to declaring JavaScript nliteral
-
o
• JSON does not have a representations fora nfunctions.
) h a deฺ
• Only values are allowed in JSON.
rs ui
sฺ nt G
m
e ude
a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks are represented in the following manner:
JSON values
u
•V Numbers: Use the number literal.
l a n
Mi • Strings: g Enclose the string
g literal inside double q
quotation marks.
• Booleans: These are either true or false.
JSON structures are represented in the following manner:
• Arrays: Must be enclosed in square brackets “[]” and elements must be comma-separated. They
can contain arrays, objects, numbers, strings, or boolean as elements.
• Objects: Must be enclosed in curly brackets “{}.” Properties are comma-separated key-value
pairs. The key for the property must be a string; therefore, it must be enclosed in double quotation
marks Val
marks. Values
es for properties can be arra
arrays,
s objects,
objects n
numbers,
mbers strings,
strings or boolean
boolean.
There is no way to represent functions in JSON because it is used to represent only data.

JavaScript and HTML5: Develop Web Applications 6 - 7


Converting to Strings

function Person(name, age){


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

this.name=name;
this.age=age;
}
Person.prototype.calculate=function(){}
var person = new Person("john", 32); e
n s
ice
b l el
var personJson =JSON.stringify(person);
fe r a
a n s
o n -tr
console.log(personJson);
s an
//output: {"name":"john","age":32} ) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
k a
s an object, array, or value to its JSON representation, use the
To convert
V u
JSON.stringify() method.
l a n
Mi Any parameter that you provide to the method is converted to a valid JSON string.

JavaScript and HTML5: Develop Web Applications 6 - 8


Converting Strings to Objects

var personJson = "{\"name\":\"john\",\"age\":32}";


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var person = JSON.parse(personJson);

console.log(person); //outputs object:object

person.toString = function(){return this.name+"- n s e


ice
"+this.age;}
b l el
f er a
s
anJohn-32
console.log(person.toString()); //outputs:
- t r
n on
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
k a
s a JSON string to the original object, array, or value used, you can use the
To convert
V u
JSON.parse() function. The string that is provided is converted to a valid value in
l a n
Mi JavaScript.
Note that there is no direct way of telling what you are going to get from the parse method. It
can be an object, array, number, string, or Boolean.
Usually, JSON is used for arrays and objects, and you need to know what to expect in
advance.
You can check whether the value is an object, array, or value by using:
p (j
var value = JSON.parse(jsonString); g);
if(value instanceof Object){
//isObject
}else if(value instanceof Array){
//isArray
}else{
//isASingleValue
}

JavaScript and HTML5: Develop Web Applications 6 - 9


Exercise

Use JSConsole and try to complete the following exercise.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Parse and generate JSON strings.

Time Limit: 15 minutes

n s e
ice
b l el
fe r a
a n s
o n -tr
s an
h a and
Exercise: JSON Parsing
) i d eฺGeneration
ฺrs t Gu
Convert objects to JSON strings and back.
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks browser, go to the JSConsole application, and run the exercise.
Open your
u
V the required JavaScript code to make the tests pass.
l a n
Add
Mi You can find more help on how to solve a particular test by clicking the result.
result

JavaScript and HTML5: Develop Web Applications 6 - 10


Topics

• JSON Object Representation


– JSON Parsing
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– JSON Generation
• The JavaScript Sandbox
• Cookies
• Local Storage
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 11


JavaScript Sandbox

Web applications run JavaScript inside a sandboxed


environment. This provides:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Better security
• Resource handling
• Isolated execution

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks running inside a web browser executes inside a controlled environment that
JavaScript
u
V several advantages to developers and users.
provides
l a n
Mi The sandboxed environment has controlled access to resources, preventing applications from
breaking the client’s machine.
For developers, it ensures that no other active application interacts with your application code,
thus providing better security and preventing race conditions, or abnormal alteration of data.

JavaScript and HTML5: Develop Web Applications 6 - 12


Sandbox Trade-Offs

In exchange for sandbox features, you lose access to features


that are found in other languages and run times, such as:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• File system I/O


• Device I/O
• Threading and concurrency
• Connections and sockets
n s e
• Native windows or frames ce
le li
• Database access a b
• Remote procedure calls or interfaces s f er
an - tr
o n
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksfor sandbox benefits, you find that many features that are commonly found in other
If you opt
V u
languages are absent.
l a n
Mi • There e e is
s no
o way
ay to access files
es o
or sto
storage
age in tthe
e cclient’s
e t s machine.
ac e
• There is no way to interact with external devices such as connected headsets, game
controllers, and so on.
• There is no concurrency or native multi-threading processing.
• You cannot establish direct connections to other servers by using raw sockets.
• You cannot open native windows or external applications in the client’s machine.
• There is no direct database access.
access
• You cannot call remote procedures or interfaces in other servers or machines.
All these interactions are possible through the use of advanced JavaScript and HTTP tricks,
for example:
• You can provide access to database data by using a REST service that is invoked by
using an HTTP request in your JavaScript application and data is returned as JSON.

JavaScript and HTML5: Develop Web Applications 6 - 13


Web Features

Although the web-based JavaScript API lacks several features


found in other languages, it compensates its shortcomings with
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

equivalent or substitute technologies.

Fil System
File S t I/O • Cookies,
C ki llocall storage
t
Threading and s e
concurrency • Timeout and intervals ice n
b l el
f er a
s Connections and
• WebSocket,
W bS k t AJAX - t r an sockets
n on
Native windows s a
• HTML5 ) h a
Frames,
i d eฺ popups
or frames. ฺrs t Gu
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
ks a
The JavaScript APIs in web applications have several restrictions and there are tasks that you
u
V accomplish as a result. In some cases, you have alternatives as listed in the graphic in
cannot
l a n
Mi the slide. In other cases, you will need to resort to alternatives such as plug-ins or stand-alone
applications.
However, before resorting to a third-party plug-in, try to use the technologies that are
available. In most cases, you can solve the problem with a combination of available solutions.
Example
Database Access: You cannot query a database directly by using JavaScript. Instead of
trying to access the database, think of the real problem. Often, you want to access a database
to obtain data. To obtain data from a server, you can use AJAX. Changing the perspective of
the problem can help you to visualize the technologies that you can use.

JavaScript and HTML5: Develop Web Applications 6 - 14


Application Data

Application data refers to the data that an application can store to


preserve user information.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

In stand-alone applications, this is usually stored in files.


In JavaScript, you can store it in:
• The server
• A cookie (client side)
n s e
• Local storage
e l ice
(HTML5 client side) bl
f e ra
a ns
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Server side storage is not covered in this course because it can be implemented with a simple
u
V
AJAX call, with the body as a JSON string object.
anTo retrieve data, you can use another AJAX call. This is discussed in detail in the lesson titled
Mil
“AJAX and WebSocket.”

JavaScript and HTML5: Develop Web Applications 6 - 15


Topics

• JSON Object Representation


– JSON Parsing
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– JSON Generation
• The JavaScript Sandbox
• Cookies
• Local Storage
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 16


Cookies

Cookies are small files stored in the client computer.


• Contain value-pair data; for example, user=John
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Have an expiration date that allows the cookie to be deleted


automatically
• Are isolated to the current application path and secure
protocol (HTTP or HTTPS)
• Are limited in size: up to 4 KB (Browsers n s e
might provide more space.) lice
a b le
• Can have usage g restricted to HTTP calls s f er
n
(no JavaScript access) -tra on
a n
h a s eฺ
) i d
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Cookies a
kswere created as the first solution to store data in the client’s machine. Their main
u
V was to save some user identification information in the client machine to resend it to
purpose
l a n
Mi the server.
Cookies are sent to the server with every HTTP request. Additionally, JavaScript may read
and modify them. The space restriction came from the fact that cookies add overhead to each
HTTP request. Cookies store key-value pairs of strings.

JavaScript and HTML5: Develop Web Applications 6 - 17


Cookie API

Cookies are set by using:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

document.cookie=CookieString

CookieString is a string that describes what data to store.


"KEY=VALUE[;EXPIRATION[;path=PATH]]"

n s e
ice
To read cookies, use: b l el
fe r a
var cookies
ki = document.cookie;
d t ki a n s
o n -tr
• This returns all the cookies for the document n as key/value
pairs separated by ;.
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks a cookie, use an expired date as the expiration date.
To remove
u
anForVexample, to delete the cookie named oracle:
Mil • document.cookie
document cookie = 'oracle=;
oracle=; expires=Thu,
expires=Thu 01 Jan 1970 00:00:01
GMT;';

JavaScript and HTML5: Develop Web Applications 6 - 18


Using Cookies

document.cookie = "name=Ed";
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

document.cookie = "username=emr";
var cookieStrings = document.cookie.split(";");
var cookies = {};
for (var i = 0; i < cookieStrings.length; i++){
var rawCookie = cookieStrings[i]
n s e
.trim().split("=");
lice
cookies[rawCookie[0]] = rawCookie[1];
a b le
} s f er
- t r an
console.log(cookies.name);//Ed
n on
a
console.log(cookies.username);//emr
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 19


Example: JavaScript Cookies

Use the JSConsole web application and run the following


example to see how to set, get, and delete cookies.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t GuiCookies
@ em uden Simple cookie example

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example in the slide. You can view or edit the example to
u
Vsome of the JavaScript code discussed in this section.
see
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 6 - 20


Topics

• JSON Object Representation


– JSON Parsing
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– JSON Generation
• The JavaScript Sandbox
• Cookies
• Local Storage
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 21


Local Storage

• Local storage is a recent feature introduced as part of the


HTML5 initiative.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• It standardizes the way applications should store data locally


in client machines.
• Features
F t off local
l l storage:
t
– Key strings-String value pairs
– 5 Megabyte storage n s e
ice
– Simpler, more focused methods than
b l el
cookies
fe r a
– Ability to be monitored with events a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
• LocalStorage is a dedicated solution for JavaScript applications to store data in the
u
V client’s machine. Local storage data is not exchanged in HTTP requests. It can be
an
Mil •
accessed only by using JavaScript.
You can store information at any time and have bigger disk quota. If you exceed the
capacity, you get a QUOTA_EXCEEDED_ERR error in the next operation.
• Because it was created with JavaScript and HTML5 in mind, it has more focused
methods and event listeners. As with cookies, data is stored in key-value pairs, both of
which must be strings.

JavaScript and HTML5: Develop Web Applications 6 - 22


Using Local Storage

Set a value:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

localStorage.setItem(key, value);

Get a value:
var value
l = l
localStorage.getItem(key);
lSt tIt (k )

Add a listener:
n s e
window.addEventListener("storage", function(event){ lice
a b le
// event.key // The named key that was modified
s f er
// event.oldValue, event.newValue // values
- t r an
// event.url // the url that triggeredn on the event
s a
}, false); h a eฺ ) id
ฺ r s u
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Tracking changes to the local storage is accomplished by using a listener on the storage
u
V
event in the window object.
an
Mil

JavaScript and HTML5: Develop Web Applications 6 - 23


Local Storage + JSON

• JavaScript objects can be represented by JSON strings.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• You can save any string with a key in the local storage.

• Combine both to save JavaScript objects in an application.

n s e
localStorage.setItem( ice
b l el
"data", JSON.stringify(object));
fe r a
a n s
o n -tr
var object =
s an
JSON.parse(localStorage.getItem("data")); ) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ksalso stringify or parse arrays directly:
You can
u
•V var array = [1,2,3,4]
l a n
Mi • var jsonArray=JSON.stringify(array);
jsonArray=JSON stringify(array);
Likewise:
• var array = JSON.parse("[1,2,3,4]");

JavaScript and HTML5: Develop Web Applications 6 - 24


Exercise

Use the JSConsole web application and try to complete the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

exercise.

Save and show the saved data by using local storage


storage.

Time Limit: 15 minutes s e


ce n
el i
a b l
fe r
a n s
o n -tr
s an
) h a deฺ
s ฺrs t Gui Local Storage
Exercise:
em uden
Save the state of an application.

a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks browser, go to the JSConsole application, and run the exercise.
Open your
u
V the required JavaScript code to implement local storage in the application. Refer to the
l a n
Add
Mi Instructions tab to get help and reference on the different functions that are available to use
the LocalStorage object.

JavaScript and HTML5: Develop Web Applications 6 - 25


Where Can I Learn More?

Resource Website
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

JSON Official Site http://json.org/

http://www.ecma-
p
ECMA JSON Data
international.org/publications/files/ECMA-ST/ECMA-
Interchange Format
404.pdf
JavaScript DOM Storage https://developer.mozilla.org/en-
n s e
API US/docs/Web/Guide/API/DOM/Storage
ice
Web Storage HTML5
http://dev.w3.org/html5/webstorage/ b l el
Standard
fe r a
HTTP State Management a n s
Mechanism (cookies) -
https://www.ietf.org/rfc/rfc2109.txt
n tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 26


Summary

In this lesson, you should have learned how to:


• Convert objects into JSON strings
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Parse JSON strings into JavaScript objects


• Store objects by using the JSON API, cookies, and local
storage

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 27


Practice 6: Overview

This practice covers the following topics:


• Practice 6-1: Saving user input by using JSON and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

LocalStorage
• Practice 6-2: Restoring saved data when a page loads

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 6 - 28


7
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Style
St l Applications
A li ti U
Using
i CSS3
and JavaScript ice n s e
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
s an Day

) h a deฺ
s ฺrs t Gui Hands-On Practice

@ em uden Lecture

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 2


Objectives

After completing this lesson, you should be able to:


• Apply CSS styles to HTML documents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Use CSS3 features to add dynamic styles to


elements with events
• Use media queries and media
data to adapt styles to different
screens n s e
ice
• Use JavaScript to add and remove styles from
b l el
elements fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 3


Topics

• Cascading Style Sheets (CSS3) Basics


– Adding a Style Sheet
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Selectors
– Adding Dynamic Styles to Elements
– CSS3 Properties
– CSS3 Box Model
– Vendor Prefixes n s e
ice
• Media Queries
b l el
• Multicolumn fe r a
a n s
• Modifying Styles with JavaScript n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 4


Cascading Style Sheets (CSS)

• CSS rule syntax:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

selector {
property_one: value_one;
property_two: value_two;
}

• Applying a style:
selector n s e
ice
/* Comments in a style sheet */
b l el
semicolon r a
sfe
h1 {
background-color: white;
tra n
color: red;
o n -
}
s an
) h a line
new i d eฺ
property value sฺrs G u
em uden t
a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
CSS 2 specifications were adopted in 1998 and CSS3 has been in development since then.
u
V
CSS3 is the third major revision of the W3C CSS specification. One of the main features of
an
Mil CSS3 is that it has been divided into several modules. You can review the current work of
these modules at http://www.w3.org/Style/CSS/current-work. In this lesson, you will find CSS3
specifications that come from CSS 2.1 and some new additions.
Cascading Style Sheets (CSS) allow you to apply a presentation to HTML documents by
defining the look-and-feel of the elements. By using CSS, you can set colors, spacing, fonts,
positions, and much more.
Anatomy of a CSS Rule
In the first box in the slide, the CSS rule syntax is shown. For a CSS rule, you have:
• Selectors, which are the HTML elements to match and apply styles
• The declaration block, which includes properties and values between curly braces
A property specifies the aspect of the selector that you want to style. The value of the property
can be specified in different units: hexadecimal, a keyword, or even a function. You can write
multiple declarations in a rule, separated with a semicolon (;).
The declaration block with the selector composes the CSS rule. The statement in the second
code in the slide reads: “The heading h1 of the HTML document should have a white
background color and a red font color.”

JavaScript and HTML5: Develop Web Applications 7 - 5


Cascading Style Sheets (CSS)

• Overriding a rule:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

h1 {
background-color:
bac g ou d co o : red
ed !
!important;
po ta t;
}

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Cascading
u
V cascading is a set of rules that assign a level of importance to each CSS style rule and
l a n
CSS
Mi define which CSS rule takes precedence and will finally style a given element. The level of
importance, or weight of a rule, is specified by the specificity of a selector, among other
criteria. When rules have the same weight, they are compared in terms of order precedence.
This means that later rules override earlier rules.
The term cascading is used because you can set styles at the top level and have
them cascade down to child elements, thus enabling you to set generic styles globally and
override them only when you need to.
!important
By appending !important to a rule, you give it a weight that is higher than the usual. This
allows you to override author style sheets. However, !important should not be used unless
there is no other option, because it breaks the natural cascading in the style sheets. The
!important keyword goes after the value and before the semicolon, as shown in the slide.
Inheritance
In the absence of any specific style declaration that is supposedly to come from the CSS
cascade, an element can take on the style properties from its parent.

JavaScript and HTML5: Develop Web Applications 7 - 6


Adding CSS to HTML

1. Inline style:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<h1 style="color:red;">The Next Big Conference for


Front-End Developers</h1>

2. Embedded style:
n s e
ice
el
<head>
<style> a b l
fe r
h1 {
a n s
color: red;
n - tr
o
an
}
</style>
h s
a deฺ
</head> )
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
There kare a
s three options to add style rules into the HTML documents: *
u
V Inline styles are applied by adding the style attribute to the opening HTML element.
1.
l a n
Mi Inline
e styles
sty es are
a e not
ot recommended
eco e ded because ttheir
e cost o
of maintenance
a te a ce is
s high.
g Too
change a style, you must update the style at all the places in the document where the
style was specified.
2. Embedded styles are applied by using the <style> element, where you can include the
CSS rules. The style element should go under the head element. The disadvantage
of this is that the CSS must be loaded every time the HTML document is loaded.
3. The best option is to add CSS rules to a separate document, and then to insert a link to
th external
the t l style
t l sheet
h t in
i the
th HTML ddocument. t Thi
This allows
ll ffor separation
ti off
presentation from content. This option is detailed in the next few slides.
* Practice these three options in JSConsole: Open “CSS Examples” for this lesson. Here, you
can modify the CSS file or the HTML file. Click Run to see the changes on the web page.

JavaScript and HTML5: Develop Web Applications 7 - 7


Adding CSS to HTML

3. Adding a style sheet:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<!DOCTYPE html>
<html>
<head>
<title>The Next Big Front-End Conference</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css" />
<script src="code.js"></script>
n s e
</head>
lice
<body>
a b le
</body>
s f er
tra
</html> n
n -
<style> a no
@import url(style.css); h a s eฺ
ฺ r s ) u id
ms dent G
</style>
e
@ Stu
a n
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
kspractice is to create and use an external style sheet. It reduces site maintenance
The best
u
V the design of the site is located in a single file. With this, you are separating the
because
l a n
Mi content from presentation. Also, users can download and cache the style sheet once in their
first visit.
A style sheet is a file with the.css extension, where you can put all the CSS rules that define
the presentation of the web page.
You can link any number of external style sheets to an HTML document. However, it is
recommended to include one long style sheet instead of several small style sheets, to
minimize the number of HTTP requests. With a single CSS file, it is cached only once, when
th fifirst’s
the t’ page content
t t iis d
downloaded.
l d d
The <link> element is used to include an external style sheet. The rel attribute must be
specified with "stylesheet" to render it as CSS. The href attribute should contain the
URL of the external style sheet that contains the CSS. If the document is internal, it can be a
relative URL and if it is external, it should be an absolute URL. There is another attribute
named media, which specifies the devices to render. When this attribute is not specified, its
value is "all", which means all devices.

JavaScript and HTML5: Develop Web Applications 7 - 8


@import
The @import directive is another way to add external style sheets. An example is shown in
the second code in the slide. However, it is recommended to use the <link> tag to add a
y sheet to avoid performance
style p issues because @import
p blocks p
parallel downloading.
g
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
i ce
b l el
fer a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 9


Selectors

1. Element type selectors:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

p {
color: blue;
font-size: 1.4em;
}

• Multiple selectors:
p, h2 {
n s e
text-transform: capitalize;
ice
}
b l el
er a
• Child selectors:
l t Only those <p> a n sf
descendants
o n -trof
aside p {
s an
<aside>
color: pink; h a de ฺ
r s ) u i
}
m sฺ nt G
@ e ude
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
an(
ks
With selectors, you can select the elements in the document to match and apply styles. There
u
V
are several options for matching elements: element type selectors, class selectors, and ID
an
Mil selectors. It is recommended to use element type and class rather than ID selectors, because
with ID selectors, the specificity is higher than the other two. Therefore, it becomes easier to
override type or class selectors than ID selectors.
Element type selectors allow you to target all the HTML elements on the web page. Type
selectors are not case-sensitive.
You can declare multiple elements in a selector group by separating them with a comma.
When elements are separated with a space, they are called descendant elements.
Examples of type selectors are shown in the slide. Remember that you can practice these
CSS examples by opening the examples for this lesson in JSConsole.

JavaScript and HTML5: Develop Web Applications 7 - 10


Selectors

2. Class selectors:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

.copyright {
font-size: smaller;
}

• Multiple classes:
.copyright.user-groups {
n s e
font-size: smaller;
ice
}
b l el
fe r a
3 ID selectors:
3. l t a n s
o n -tr
#section-1 {
s an
color: green;
) h a deฺ
}
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
s a
A classkselector targets all the elements with a specific class. It begins with a period symbol
u
n(.).V
a Multiple classes are allowed; for example, the second code in the slide states to match any
Mil element that has both classes. In the example, there is one element that does match: <p
class="user-groups copyright">&copy; 2014 Front End User Groups</p>.
ID Selector
The ID selector targets the element with a specific ID. This selector begins with the pound or
hash (#) symbol. The example in the slide marks the elements under the section with ID =
"section-1" green.
The ID selector has more weight than the class or type selector. IDs cannot match more than
one element per HTML document.

JavaScript and HTML5: Develop Web Applications 7 - 11


Combinators

• Universal selectors:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

* {
color: blue;
}

• Descendant selector:
#section-2 p {
n s e
font-weight: bold;
ice
}
b l el
fe r a
• Child selectors:
l t a n s
o n -tr
#section-2 > article > header > h1 { a n
color: red; h a s eฺ
ฺ r s ) u id
ms dent G
}
e
@ Stu
a n
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks Selector
Universal
u
V this selector, you can select all the elements on your web page. It affects from the root to
l a n
With
Mi the last child. It uses an asterisk (*).
( ).
Combinators
With combinators, you can specify relationships between selectors and combine them. If you
think about the HTML element as a family tree, with parents and children, you will notice that
there are hierarchies between selectors, detailed in the following paragraphs.
Descendant Selectors
Descendant
D d t selectors
l t apply
l a style
t l rule
l tto allll elements
l t th
thatt are d
descendants
d t off th
the specified
ifi d
element. They target children, grandchildren, and so on. You can use descendent selectors to
avoid redundant classes.
The example in the slide targets those paragraphs that are descendants of the element with
id = "section-2".
Child Selectors
They are the target elements that are immediate children of the specified element
The element. The child
combinator uses the greater-than sign (>).

JavaScript and HTML5: Develop Web Applications 7 - 12


Combinators

• Adjacent sibling selectors:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

h1 + p {
color: purple;
}

• General sibling selector:


header ~ p {
n s e
ice
el
color: orange;
}
a b l
fe r
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks (Adjacent) Sibling Selectors
Subsequent
u
V selector targets elements that are next to each other and have the same parent. It uses
l a n
This
Mi the plus character (+). The example in the slide shows a rule that selects any paragraph
element that immediately follows a level-one heading element.
General Sibling Selectors
When using this combinator, the second selector does not have to immediately follow the first.
This selector targets all elements that are siblings of the specified element. It uses the tilde
character (~).

JavaScript and HTML5: Develop Web Applications 7 - 13


Attribute Selectors

• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

E[attr]
E[attr=val]

• Example of attribute:
input[required] {
n s e
background-color: yellow;
ice
}
b l el
fe r a
• Example
E l off attribute
tt ib t value:
l a n s
o n -tr
input[type="email"] {
s an
border: 1px dashed black;
) h a deฺ
}
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ksselector, you can target a rule and apply CSS to an element based on the attributes
With this
u
Vtheir values.
and
l a n
Mi

JavaScript and HTML5: Develop Web Applications 7 - 14


Attribute Selectors

• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

E[attr^=val] // Starts with


E[attr*=val] // Contains
E[attr$=val] // Ends with

• Starts with example:


a[href^="#section-"] {
color: red; n s e
ice
}
b l el
fe r a
• Contains
C t i an example:
l a n s
n - tr
o
an
a[href*="tion-"] {
color: orange;
h s
a deฺ
} )
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks Selectors
Substring
u
V can also target elements based on the substrings of an attribute. For this, you have three
l a n
You
Mi options:
1. Starts with (E[attr^=val]): Targets an element with the attr attribute whose value
begins with the prefix "val". The selector example in the slide shows an HTML anchor
a with an href attribute whose value starts with "#section-", setting in red three
anchors with the href attribute: "#section-1", "#section-2", and "#section-
3".
2. Contains (E[attr*=val]): Targets an element with the attr attribute whose value
contains
t i ththe substring
b t i "val". The
Th selector
l t example l iin th
the slide
lid ttargets
t th
the same th
three
anchors as in the first example, but by looking for the substring "tion-".
3. Ends with (E[attr$=val]): Targets an element with the attr attribute whose value
ends with the suffix "val"
Note:
It is also possible to have multiple attribute matches; for example:
input[type="text"][name="name"] { background-color: yellow }, which
requires that all attribute matches must be true.

JavaScript and HTML5: Develop Web Applications 7 - 15


Pseudo-Class Selectors
Pseudo-
Pseudo Matches Pseudo-
Pseudo Matches
class class
:link Any link that the user has :target Target elements
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

not visited yet


:visited Any visited link :first-child The first child of an
element
:hover A link as the user passes :last-child The last child of an
the cursor over it element
:active An element being activated :nth- The n child of an element
n s e
by the user child(n)
ice
:focus An element that has the :nth-of- b
The n child of a particularl el
focus type(n) yp of its p
type, f
parent e ra
t r a ns
:enabled Any element in enabled :root
o n - that is the
The element
state
a n the document
root of
:checked Radio option or check box :not ha
s Aneelement
ฺ not
r s ) u i d
in selected state
s ฺ t G represented by its

@ em uden argument

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
With pseudo-classes, you can target elements that the user is interacting with within the
V u
document based on their position or state. Pseudo-classes are not explicitly present in the
l a n
Mi HTML document.
The first table in the slide lists pseudo-classes that are classified as dynamic and UI element
states: :link, :visited, :hover, :active, :focus, :enabled, and :checked. The
target to match is shown in the second column of the tables.
The second table in the slide shows the :target pseudo-class, followed by some structural
pseudo-classes: :first-child, :last-child, :nth-child, :nth-of-type, :root,
and :not. With the :target pseudo-class, the target elements can be represented. Target
elements are those URIs ending with "#", "#" followed by an anchor identifier (for example
example,
http://.../lesson07/css_examples/index.html#section-2 in JSConsole).
Note:
The list of pseudo-classes is not limited to the ones referred to in the table in the slide. To
know more about pseudo-classes, go to: http://www.w3.org/TR/css3-ui/ and
http://www.w3.org/TR/selectors/#pseudo-classes.
As a practice
practice, try
tr to increase the font si
size
e and weight
eight of the last paragraph of the Speakers
section in the JSConsole example: section#section-1 p:last-child {font-size:
18px; font-weight: bold;} or for :target: section:target {background:
wheat;}.
JavaScript and HTML5: Develop Web Applications 7 - 16
Pseudo-Element Selectors

Pseudo-Element Matches
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

::first-line The first line of a given element

::first-letter
fi l Th fifirstt lletter
The tt off an element
l t

::before Add content preceding a given element e


n s
ice
::after Add generated content after an element b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k s a
Pseudo-elements allow you to target and style parts in the document that are not reachable
u
V DOM; for example, ::first-line, ::first-letter, ::before, and ::after,
through
l a n
Mi as described in the table in the slide.
As a practice, try to increase the font size of the first letter of each paragraph in the Speakers
section in the example in JSConsole: #section-1 p::first-letter { font-size:
200%; }.
A convention is to put one colon (:) before pseudo-classes and two colons (::) before
pseudo-elements. However, it is possible to specify pseudo-elements with a single colon.

JavaScript and HTML5: Develop Web Applications 7 - 17


Adding Dynamic Styles to Elements

• On hover:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

input[type=submit]:hover {
cursor: pointer;
}

• On focus:
input[type=text]:focus {
background-color: lightyellow; n s e
ice
}
b l el
fe r a
• On
O active:
ti a n s
n - tr
a:active { o
font-size:150%;
s an
}
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k s a
With pseudo-classes, you can modify element properties based on user interaction.
V u
Previously, you saw some of the pseudo-classes: :link, :visited, :hover, :active,
l a n
Mi :focus, :enabled, and :checked. With the examples in the slide, you will see how these
pseudo-classes add dynamic styling. Try the code in the slide in JSConsole, add them to the
CSS file, and click Run to see how the cursor changes when it passes over the Submit
button, how the background color changes when an input has the focus, or how the font size
increases when the link is active (that is, when the user clicks it), and so on.

JavaScript and HTML5: Develop Web Applications 7 - 18


CSS3 Properties: Fonts
generic font
family
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

p { font-family: "Trebuchet MS", Verdana, sans-serif; }

@font-face:
@font face:
@font-face {
font-family: "my paragraphtext";
n s e
src: url(WebFont.woff) format("woff"),
lice
url(WebFont.ttf) format("truetype");
a b le
}
s f er
p {
- t r an
font-size: 12px;
n o n
s a
font-family: "my paragraphtext", Helvetica, sans-
serif; h a e ฺ
r s generic
) u i dfont
font-weight: normal;
sฺ family G
} e m
@ Stuent d
a n
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The typeface, or font-family, of a formatting text, is set as shown in the first code in the
u
V
slide. The font-family property in the CSS rule specifies to look for the font family on the
an
Mil user’s computer in the given order.
If none exists, the default is used, which is sans-serif in the example. It is recommended
to append a generic font family (serif, sans-serif, cursive, fantasy, and
monospace) as a default alternative.
Font Size
The font-size property allows you to increase or decrease the size of a font.
Co
Commono uunits
ts of
o font
o t size
s e include
c ude p
px,, %, a
and
deem. With
t ppx,, pixels
p esa are
eaalways
ays tthe
e sa
same
e ssize,
e,
no matter what; em is the same length as the width of the letter.
@font-face
@font-face has been re-introduced for the CSS3 Fonts module
(http://www.w3.org/TR/css3-fonts/). It allows the user to download a font from the web page.
The example in the slide downloads the font WebFont, and uses it when rendering text within
paragraph elements. It tries to download the Web Open Font Format (WOFF) font. If it is not
possible, it downloads the TTF font.

JavaScript and HTML5: Develop Web Applications 7 - 19


There are several formats: WOFF, SVG, Embedded Open Type (EOT), OpenType, and
TrueType (OTF/TTF). It is also possible to use a local copy of a given font. In this case,
local() can be used instead of url().
It is recommended that you specify the fonts to use for different styles (bold, italic, and so on)
to avoid variation.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
i ce
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 20


CSS3 Properties: Colors

• RGB Color:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

p {
color: #800000; // or color: maroon;
color: rgb(128, 0, 0); // in functional notation
color:
l rgba(128,
b (128 0,
0 0,
0 0.5);//
0 5) // rgb
b with
ith transparency
t
}
Try this code in
n s e
• HSL: lice
JSConsole.
bl e
p { fe r a
color: hsl(0, 100%, 25%); // maroonans
color: hsla(0, 100%, 25%, 0.5); o n
// maroon-tr with
s eฺ a ntransparency
//
} h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks property allows you to set the foreground color of an element’s text content. You
The color
u
Vdeclare color in two ways:
can
l a n
Mi 1. RGB G Color:
Co o You ou ca
can set tthe
e co
color
o based o
on hexadecimal
e adec a cocombinations
b at o s oof red,
ed, g
green,
ee ,
and blue. The hexadecimal (hex) notation starts with a hash symbol (#), followed by a
six-character combination of numbers and letters. You can also set the RGB values in
functional notation with integer values (up to 255) or percentage values (up to 100%).
An example of RGB color is shown in the first code in the slide.
2. HSL Color: You can also encode colors as a triple (Hue, Saturation, Lightness). HSL is
more intuitive than RGB because it is based on a 360° color wheel. Hue is selected by
choosing a degree in the wheel (for example
example, Yellow at 60°
60 , Green at 120
120°, Red at 360°
360 ,
and so on), and then choosing a variation with two values for saturation and lightness.
There are also methods to set an RGB or HSL color with transparency, as shown in the slide.
'a' stands for alpha and the last parameter specifies the alpha transparency of the element.
The value is between 0.0 and 1.0. The keyword 'transparent' is also allowed as a color
value.
You can set the background
g color of an element with background-color;.
g ;
To learn more about colors, look at the following URL: http://www.w3.org/TR/css3-color/.

JavaScript and HTML5: Develop Web Applications 7 - 21


CSS Box Model

The top
Box
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

margin
left right
e
Text l el ice n s
border r a b
n s fe
-tr a
n o n padding
content a
s eฺ
h a
ฺ r s ) u id
s nt G
mbottom
@ e u de
n
a is S t
k s
n ฺ vu se th Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

( m ila to u
k
The Box s an in CSS states that every HTML element displayed consists of one or more
Model
V u These boxes, as shown in the graphic in the slide, are surrounded by some space or
boxes.
an
Mil padding. • Content: The content could be a paragraph, list, header, or object.
• Padding: The padding area is immediately between the content area and the border.
• Border: This is the edge that encloses the content and padding.
• Margin: It is the space between the border and the box containing the next element.
There are several length units for these properties. However, we are currently limiting to %,
tthe
e pe
percentage
ce tage of
o the
t e containing
co ta gbblock’s
oc s width;
dt ; e
em,, tthe
e height
eg to of tthe
e font;
o t; a
and
dppx,, for
o sc
screen
ee
CSS.
The individual sides of a box are: top, right, bottom, and left. The width of each side
can be specified separately. When they are not specified, the value is the same for all four
sides. When they are specified, the four values are assigned in the clockwise order: top,
right, bottom, and left. There is also a shorthand: Two lengths set the top and bottom
widths to the first value and the left and right to the second value. If three lengths are
specified the top
specified, t is set to the first value
value, the left
l ft and righti ht are set to the second,
second and the
bottom is set to the third.

JavaScript and HTML5: Develop Web Applications 7 - 22


CSS Box Model
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Sizingks a
V uthe width and height properties, you can specify the width and height of the content
an
With
Mil area, padding area, or border area.
With box-sizing, you can specify the box model to use to calculate widths and heights. The
possible values are content-box, padding-box, or border-box.
Exercise:
1. Run “CSS Examples” for this lesson in JSConsole to open the index.html file in
Firefox.
2 Select Tools > Web Developer > Inspector to open the Inspector
2. Inspector. There
There, you will find the
Box Model button on the top right as shown in the figure in the slide.
3. Click Box Model button and move the cursor over the different elements on the web
page. When you click one of the elements on the web page, you see its box model and
its dimensions.

JavaScript and HTML5: Develop Web Applications 7 - 23


Display, Alignment, and Position
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

fl t right;
float: ht

n s e
ice
b l el
fe r a
a n s
n - tr
float: o
s an
left; h a deฺ
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks Boxes
Block-Level
u
V are the building blocks. They indicate how the boxes are positioned with respect to other
l a n
They
Mi boxes. The display: block; property does not allow elements next to it, whereas display: inline; does. An inline element sits on the line of text and does not have width,
height, padding, or margin.
The default height of a block-level box is the height necessary to contain the box’s content.
Positioning
Box position can be calculated with respect to the block where the box is contained. Several
a ues a
values are
eaavailable
a ab e for
o tthe
e pos t o p
position property:
ope ty
1. Absolute (position: absolute): The element can be moved by using top, right,
bottom, and left.
2. Relative (position: relative): If the element is moved, the original space it took is
preserved.
3. Fixed (position: fixed): Elements with this position do not move when the page is
scrolled.

JavaScript and HTML5: Develop Web Applications 7 - 24


There is also static, center, and page positioning. The default positioning for all elements
is position:static. For more information about positioning, go to:
http://www.w3.org/TR/2012/WD-css3-positioning-20120207/.
Box position is not limited to its container block. It can also cross the edges with the
overflow property.
float
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

The float property allows text to wrap around images. It takes the element from the normal
flow, and determines on which side of the container the element floats. The values allowed
are left, right, and none.
Tables
With the display property, it is also possible to force non-table elements to behave like table
elements. Some of the CSS rules are display: table;, display: table-row;, and
display: table-cell;.
n s e
i ce
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 25


Example: Box Model

Use the JSConsole web application and run the following


example to change some CSS properties for an element on the
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

web page.

Ti
Time Li
Limit:
it 5 minutes
i t

n s e
ice
b l el
f er a
T
Try this
thi s
an section
ti
n - t r
inoJSConsole.
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksexample, in the styles.css file:
For this
u
an 1.V Change the display property for the paragraph p to inline and see what happens
Mil with
t the
t e paragraphs
pa ag ap s o
on tthe
e web
eb page
2. Add a position property for the .box selector, assign it different values, and see what
happens with the box on the web page
3. Add a float property to the .box selector, assign it left and right values, and see
what happens with the box on the web page

JavaScript and HTML5: Develop Web Applications 7 - 26


Vendor Prefixes
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Prefix Browser Examples

-ms-
ms Microsoft .mySelector
mySelector {
-moz-border-image:url(border.png) 30
30 repeat; /* Firefox */
-moz- Mozilla -webkit-border-image:url(border.png) 30
n s e
30 repeat; /* Safari */ ice
-o-border-image:url(border.png) 30 30 b l el
-o- Opera
repeat; /* Opera */ fe r a
a n s
-webkit- Safari and Chrome
border-image:url(border.png) 30 30
repeat; n - tr
o
}
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksPrefixes
Vendor
u
V prefixes allow browsers to try out the new features of CSS before they are finalized.
l a n
Vendor
Mi The example in the slide shows a new feature (at the time of writing this course) of CSS3
called border images (http://www.w3.org/TR/css3-background/#border-image) where authors
can specify an image as a border style. It is recommended to add the property to the rule
without a prefix (highlighted in blue in the slide), because when the feature becomes a
standard across the browsers, prefixes are not needed anymore.
Modernizr
Modernizr is a JavaScript library to detect the availability of native implementations. When a
user visits a site, Modernizr runs and detects support for CSS3 and HTML5 features, and then
it adds classes to the html element based on what the user’s browser supports and does not
support. The web page is at http://modernizr.com/.
HTML5 Boilerplate
A good starting point for your project is the HTML5 Boilerplate: http://html5boilerplate.com/. It
is an HTML5 template with the best practices when building web pages. It includes polyfills,
and tools such
s ch Modernizr
Moderni r.

JavaScript and HTML5: Develop Web Applications 7 - 27


Topics

• Cascading Style Sheets (CSS3) Basics


• Media Queries
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Multicolumn
• Modifying Styles with JavaScript

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 28


Media Queries
media
• CSS @media rule: feature
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

@media screen and (max-width: 750px){


media
/* put your styles here */
type
}

n s e
• <link> media attribute and in @import:
li ce
<link rel="stylesheet" media="screen and (max-width:ab l e
468px)" href
468px) href="mobile.css">
mobile.css > s f er
<link rel="stylesheet" media="screen and (min-width: - t r an
768px)" href="screen.css"> n on
s a
) h a
i d eฺ
ฺrs t Gu
@import url(smartphone.css) screen and (max-width:
s
em uden
468px);

a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
A media a
ksquery tests for some capabilities of the device that is used to view the page. It returns
u
ntrueVif the media type specified in the query matches the media type of the device.
a With @media, you can provide different CSS, depending on the media. Its purpose is to alter
Mil
the layout of a site based on viewport sizes. Viewport is the content area within the browser
window.
The media query rule syntax is shown in the first code in the slide. The query in the slide
specifies: Apply the styles within the block for the screen media type only and if the width of
the browser window is 750 pixels or less.
Multiple media queries can be listed in a single CSS rule, separated by commas. You can use
the and operator for multiples conditions and the or operator (or commas) to apply the same
CSS rule to different size ranges.
You can use media queries in the <link> tag with the media attribute or write the media
query in an @import rule. The recommended way is to write media query rules inside a style
sheet.

JavaScript and HTML5: Develop Web Applications 7 - 29


The media types allowed are: screen, print, braille, handheld, projection, tty,
tv, embossed, speech, and all. The all media type includes all media types. The most
commonly used media types are screen, for color computed screens, and print, for printed
material.
What can media queries test for?
The media features that can be tested are: width, height, device-width, device-
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

height, orientation, aspect-ratio, device-aspect-ratio, color, color-


index, monochrome, resolution, scan, and grid. You can prefix the feature with min-
or max- to indicate a minimum or maximum value (except for orientation, scan, and
grid).
• width: The width of the display area in the output device (such as a browser window)
• height: The height of the display in the output device
• device-width: The screen width of a device e
n s
• device-height: The screen height of a device
i ce
• orientation: The orientation of the output device: portrait or landscape b l el
• aspect-ratio:
p The ratio of the width to the height
g based on the displayfer a
p y area ((viewport)
p )
width and height (that is, 16/9) a n s
n - tr
• o
device-aspect-ratio: Similar to aspect-ratio but based on the device-width and device-
height s an
) h a deฺ
ฺrs t Gui
• color: The number of bits per color component
• s
color-index: The number of entries in the color lookup table of the output device
• monochrome: Number of bits p@ em uden
per p
pixel in the monochrome frame buffer
a n S t
• s
uk e thi s
resolution: Density of pixels of the output device in dpi (dots per inch); for example,
ฺ v
an
min-resolution: 300dpi s
• (mil to u
scan: Scanning process of TV output devices
n

u ksa
grid: Whether or not the device is grid or bitmap
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 30


Media Queries

• Using the only keyword:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

@media only screen and (min-width: 480px)

• Using the not keyword:

n s e
not screen and (max-width: 768px)
ice
b l el
fe r a
• Adjusting
Adj ti th the viewport:
i t a n s
o n -tr
<meta name="viewport" content="width=device-width, s an
) h a deฺ
ฺrs t Gui
initial-scale=1.0">
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
You can
k a
suse the only keyword to hide styles from browsers that do not support media
u
V For modern web browsers, the only keyword is transparent. They process the
queries.
l a n
Mi media query as if the only keyword does not exist. The first code in the slide shows an
example of only.
The not keyword reverses the logic of the query. However, it must be placed at the beginning
of the query. The second code in the slide applies the styles for any media type and size
except a visual browser (screen) with a maximum screen width of 768.
The last code in the slide shows an example of how to force mobile browsers to expose their
true dimensions and disable zoom by using the <meta> tag.

JavaScript and HTML5: Develop Web Applications 7 - 31


Example: Media Queries
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
Responsive n s
Design Mode
n - tra
o
an
button
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Testing a
ksthe Responsiveness of a Web Page
u
In V
n Firefox, you can select the size to test, and automatically resize the page that you are
i l a
M viewing into a frame with the required width.
In this example, you run media queries against different viewports in Firefox:
1. Click the Run button (the button with the play symbol) of “Media Queries” for this lesson
in JSConsole.
2. Select Tools > Web Developer > Inspector to open the Inspector. There, you will find the
Responsive Design Mode button on the right as shown in the screenshot in the slide.
3 Click the Responsive Design Mode button and resize the screen window on the web
3.
page. The background color changes, depending on the screen resolution. Also, the
“Landscape Orientation” footer caption appears when you are in such orientation.
To read more about media queries, go to: http://www.w3.org/TR/css3-mediaqueries/.

JavaScript and HTML5: Develop Web Applications 7 - 32


Topics

• Cascading Style Sheets (CSS3) Basics


• Media Queries
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Multicolumn
• Modifying Styles with JavaScript

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 33


Multicolumn
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
.columns
columns {
a n s
column-width: 13em;
n - tr
o
column-gap: 1em;
s an
column-rule: 1px solid #000;
ha ideฺ
} rs) s ฺ t G u
@ emstyle,
width,
u d n color
eand
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The content of a Multicolumn element flows from one column to the next. The following are
u
V
some of the main properties to style an element with Multicolumn:
an
Mil p
• column-width: Specifies the width of each column. If this p
means that the width will be dictated by other properties.
property
p y is set to auto,, it

• column-count: Specifies the number of columns. The auto value applies for this
property too. You can use either column-width or column-count, but not both.
• column-gap: Allows you to add a space between columns
• column-rule: Allows you to draw a rule in the center of the gap
• columns: Is a shorthand p
property
p y to set column-width and column-count

JavaScript and HTML5: Develop Web Applications 7 - 34


Example: Multicolumn

Use the JSConsole web application and run the following


example to see the Multicolumn layout in action.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 5 minutes

n s e
ice
b l el
f er a
T
Try this
thi s
an section
ti
n - t r
inoJSConsole.
n
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
kscolumn-width with column-count in the “Multicolumn” example for this lesson in
Replace
V u
JSConsole. Also, try resizing the browser window and see how Multicolumn behaves.
l a n
Mi Notice in the example that the vendor prefixes, –webkit
webkit and –moz,
moz, are used, because not all
browsers support these properties unprefixed.

JavaScript and HTML5: Develop Web Applications 7 - 35


Topics

• Cascading Style Sheets (CSS3) Basics


• Media Queries
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Multicolumn
• Modifying Styles with JavaScript

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 36


Modifying Styles with JavaScript

• HTML:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<body>
<button onclick="changeBox()">Change box style</button>
<div id="box">
<h1>I am in a box</h1>
</div>
/di
</body>

n s e
• JS function: ice
var changeBox = function (event) { b l el
console.log("changeBox function called"); fe r a
a n s
var box = document.getElementById("box");
n - tr
box.style.backgroundColor = "#ff9966";
o
box.style.width = "280px";
s an
box.style.float = "left";
) h a deฺ
box.style.borderStyle = "dotted";
s ฺrs t Gui
};
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
You can a
schange the style of a document dynamically with JavaScript. The code in the slide
u
V the HTML and JavaScript parts to dynamically change the style of the div element by
shows
l a n
Mi manipulating its style property.
Because dashes are not allowed in variable names, camel case is used instead. In this
example, background-color and border-style in CSS are changed to
backgroundColor and borderStyle in JavaScript.
The code in the slide is also in the “CSS and JavaScript” example for this lesson in
JSConsole. Try to modify more styles by using the JavaScript code.
With JavaScript, you can modify a style sheet, a CSS rule, or an element in DOM.
The style sheets can be found in the document.styleSheets object, which returns the list
of style sheets used on the web page. Then, you can refer to a specific style sheet with the
index of the array, for example document.styleSheets[0].
To add a rule to the style sheet, you can use the insertRule method, or addRule for IE
before version 9.

JavaScript and HTML5: Develop Web Applications 7 - 37


Where Can I Learn More?

Resource Website
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

CSS Validation Service http://jigsaw.w3.org/css-validator/

CSS Current Work http://www.w3.org/Style/CSS/current-work


http://www.w3.org/Style/CSS/current work

CSS Color Module Level 3 http://www.w3.org/TR/css3-color/


CSS Positioned Layout http://www.w3.org/TR/2012/WD-css3-positioning-
n s e
Module Level 3 20120207/
ice
b l el
CSS basic box model http://www.w3.org/TR/2007/WD-css3-box-20070809/
f e ra
Media Queries W3C a ns
http://www.w3.org/TR/2012/REC-css3-mediaqueries-
t r
Recommendation 20120619/ o n -
s an
CSS Multicolumn Layout a deฺ
http://www.w3.org/TR/2011/CR-css3-multicol-
) h
ฺrs t Gui
Module 20110412/
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
ks a
u
anV
Mil

JavaScript and HTML5: Develop Web Applications 7 - 38


Summary

In this lesson, you should have learned how to:


• Apply CSS styles to HTML documents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Use CSS3 features to add dynamic styles to elements with


events
• Use Media Queries and media data to adapt styles to different
screens
• Use JavaScript to add and remove styles from elements n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 7 - 39


Practice 7: Overview

This practice covers the following topic:


• 7.1: Styling Elements with CSS3
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n mil to u
(
In this k s a
practice, you write CSS rules to style elements in the document.
u
anV
Mil

JavaScript and HTML5: Develop Web Applications 7 - 40


8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Advanced JavaScript ice n s e


b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
s an Day

) h a deฺ
s ฺrs t Gui Hands-On Practice

@ em uden Lecture

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 8 - 2


Objectives

After completing this lesson, you should be able to:


• Define functions as value types
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Create closures and explain the variable scope


• Write JavaScript functions as modules
• Create drag-and-drop interactions
with JavaScript
n s e
• Create JavaScript timers and ce
el i
delays to create animations in HTML b l
fe r a
• Use the HTML5 canvas object to draw on pages n s
- tr a
o n
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 8 - 3


Topics

• JavaScript Functions
– Functions as Values
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Functions and Variable Scopes


– Modules
• Prototypes
• HTML5 Drag and Drop
• Delays and Intervals n s e
ice
• HTML5 Canvas b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 8 - 4


Topics

• JavaScript Functions
– Functions as Values
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Functions and Variable Scopes


– Modules
• Prototypes
• HTML5 Drag and Drop
• Delays and Intervals n s e
ice
• HTML5 Canvas b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 8 - 5


JavaScript Functions as Values

In JavaScript, functions are another value type.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var sum = function(a,b){return a+b;}

A function can expect a function as a parameter.

n s e
function invoke(fn){ return fn(2,3); } ice
b l el
fe r a
Y can use a function
You f ti as a parameter.
t a n s
o n -tr
s an
invoke(sum); // 5
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks in JavaScript is another value type that can be assigned to variables.
A function
u
V the variable declaration (var x = function(){};) and function declaration
l a n
Although
Mi (function x(){}) might look similar, they have a very subtle difference in how the
JavaScript interpreter processes them. Function declarations are always loaded first. Variable
declarations are processed when their statement is processed.
You can invoke a function that is declared by using the function name() {} syntax any
time. Functions that are declared by using var name = function(); can be used only after
the declaration.
fun(); // OK
varfun(); // ERROR
var varfun = function(){};
function fun(){}
fun(); // OK
varfun(); // OK

JavaScript and HTML5: Develop Web Applications 8 - 6


JavaScript Function: this Reference

In JavaScript, all functions have a this reference.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function fun(){
console.log(this.toString());
}

n s e
this refers to the object that is used to invoke the function. ice
b l el
f er a
var objectbj t = {value:12,
{ l 12 fun:function(){
f f ti (){ an s
- t r
console.log(this.value); n on
s a
}};
) h a
i d eฺ
object.fun() // printsm12 sฺrs nt Gu
@ e ude
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks have a this reference that stores the object or context in which the function is
All functions
V u
called.
l a n
Mi • If yyou invoke an object j method,, the this reference will be the object
j itself.
• If you call a function by using the new operator to create a new object, the this
reference will be the newly created object.
• If you call a global function, the this reference will be the function itself.

JavaScript and HTML5: Develop Web Applications 8 - 7


Function Methods

• call and apply methods invoke a function by setting the


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

this property for the current invocation.

function myFunction() {
console.log(this.myProperty);
}
var myObj = { n s e
ice
el
myProperty : 15
};
a b l
fe r
myFunction.call(myObj);
a n s
15
n - tr
myFunction.apply(myObj); o
15
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksmethods allow you to modify how a function works. call and apply enable you to
Function
u
setVthe context that the function will use. This effectively changes the context of the function.
l a n
Mi Using the call and apply methods is also known as indirect call. • Function.prototype.apply(thisContext, arrArgs);
• Function.prototype.call(thisContext, arg1, arg2, arg3, ...,
argN);
These methods allow you to invoke a function and to explicitly set any object of your choice
as the function context. Take a look at the syntax for these functions in the slide. The first
argument for both call() and apply() is the context object for the function. Both methods
are similar,
i il withith the
th slight
li ht diff
difference th
thatt the
th apply() method
th d lets
l t you pass iin allll arguments
t
as a single array.

JavaScript and HTML5: Develop Web Applications 8 - 8


Function Methods

• Function.prototype.toString():
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

>> outer.toString()

"function outer() {
var x = "I am declared in the outer function";
function inner()
{
console.log(x); } inner();
}"

n s e
• Function.prototype.bind(): ice
b l el
var myObj = {
f er a
myVar
y : "Hello there!",
,
myObj.greet()
Ob s
at()
n returns
t
greet: function () {
- t r
innerGreet = function(name) {
n
"Helloon there! Duke"
console.log(this.myVar + name);
s a
};
innerGreet.bind(this," Duke")();) h a
i d eฺ
}
s ฺrs t Gu
};
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
s a
• Function.prototype.toString():
k It returns a string with the source code of the
u
V function. An example is shown in the first code in the slide, where the toString()
an
Mil •
method of the function that was shown in the previous slide is called.
Function.prototype.bind(): This method returns a new function. The new
function, when called, invokes the target function with the this keyword and the
arguments specified. An example is shown in the second code in the slide. It is the
same as the previous example with this and that, but the bind method is used here.
In this case, it is possible to reach the myObj.myVar value in the innerGreet function
because we are specifying which this to use (myObj) when calling the innerGreet
function.
Also note that in the bind method, we are specifying one argument to send by default
("Duke") to the innerGreet function. When we call the innerGreet function, this
argument will always be sent, even though we do not send any argument when the
function is called, as shown in the example.

JavaScript and HTML5: Develop Web Applications 8 - 9


Function Default Value

If you want to use a default value for a function parameter, you


must check the value for each parameter.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function x(a){
a = a || "defaultValue";
console.log(a);
n s e
}
ice
x(); // defaultValue; b l el
fe r a
x(null); // defaultValue;
a n s
n - tr
x("a"); // a o
s an
x(false); // defaultValue;
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
This iskasquick way of having default values in functions. Remember that you may need to
V ufor specific values sometimes because the statement in the slide will set the default
check
an
Mil value for the parameter for all values that evaluate to false. The values false, undefined, null, "", or NaN will be replaced by the default value. To
prevent this, you will need to make explicit IF statements for these values.

JavaScript and HTML5: Develop Web Applications 8 - 10


Callbacks

• Functions as parameters are commonly found as callbacks.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Callbacks are functions that are invoked when a process is


complete or some condition is met.

• You have been using callbacks with the HTML5 events!


n s e
ice
window.addEventListener("load", b l el
fe r a
function(event){ … } );
a n s
n - tr
o
s an
) h a deฺ
ฺrs t Gui
Callback!
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks are widely used in JavaScript because they allow you to provide a function as a
Callbacks
V u
parameter to another function.
l a n
Mi

JavaScript and HTML5: Develop Web Applications 8 - 11


Callbacks

You can even declare the callback function separately.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var onWindowLoad = function(event){ … };

window.addEventListener("load", onWindowLoad);

n s e
ice
Use a function as a parameter. b l el
f e ra
t r a ns
o n -
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Callbacks do not need to be declared inside the function invocation. You can use any function
u
V
as a callback parameter.
anBecause of the dynamic nature of JavaScript, you can send any function, even if it has a
Mil
different set of parameters than what is expected in the calling function.

JavaScript and HTML5: Develop Web Applications 8 - 12


Caution

A common mistake is invoking the function when it is used as a


parameter instead of sending the function.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Wrong:
window.addEventListener("load",onWindowLoad());

n s e
Function invocation
e l ice
r a bl
Right: n s fe
on
window.addEventListener("load", onWindowLoad); -tra
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The function syntax is as follows:
u
V
• Declaration: function name() {}
an
Mil • Invocation: name();
• Reference: var x = name;
• Variable declaration var y = function(){};
When you declare a function as a variable, you are actually creating an anonymous function
and assigning it to a variable name.

JavaScript and HTML5: Develop Web Applications 8 - 13


JavaScript Functions and Default Values

Use the JSConsole web application and run the following


example to see how JavaScript functions work.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 3 minutes

n s e
lice
ble
JavaScript Variables and Functions
ra
f e
a ns
Try this in o n -tr
JSConsole.
s an
) h a deฺ
ฺrsDefault i
uValues
s
m dent G Default values for function parameters
e
@ Stu
a n
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Open JSConsole and look for the examples in the slide. You can view or edit the examples to
u
V
see some of the JavaScript code discussed in this section.
anLook at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
Mil
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 14


JavaScript Array Extended API

JavaScript Arrays contain many methods that use closures for


array manipulation.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Array.sort(callback)
function callback(val1, val2)
callback returns 0 if values are equal
equal, a positive value if val1
should go before val2, and a negative value if val1 should
go after val2. e
n s
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks API is especially useful when dealing with arrays of objects because you can
The callback
u
V on the object instances and get access to their properties.
operate
l a n
Mi Given a person object with the “name”
name and “age”
age properties, you can sort an array of person
objects by name by using:
persons.sort(function(personA, personB){
return personA.name>personB.name?1:-1;
});
Or sort by age by using:
persons.sort(function(personA, personB){
{
return personA.age>personB.age;
});

JavaScript and HTML5: Develop Web Applications 8 - 15


JavaScript Array Extended API

• Array.forEach(callback)
function callback(value, index, array)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

executes the callback for each element in the array.

• Array.every(callback)
( llb k)
function callback(value, index, array)
returns true if the callback returns true for all the elements in s e
n
the array. lice e
r a bl
s fe
- t r an
no n
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The forEach method is very useful when you want to apply a function on all the elements of
u
V
the array.
an
Mil To print the contents of the persons array from the previous example, you can use a forEach
function.
persons.forEach(function(person, index){
console.log(index+":"+person.name+"["+person.age+"]");
});
To ensure that every method tests that all the objects meet a condition defined in the callback,
the callback function must return a Boolean value
value.
Check whether all the person objects are at least 10 years old:
var every10yo = persons.every(function(person){
return person.age>10;
});

JavaScript and HTML5: Develop Web Applications 8 - 16


JavaScript Array Extended API

• Array.some(callback)
function callback(value, index, array)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

returns true if the callback returns true for at least one of the
elements in the array.

• Array.filter(callback)
function callback(value, index, array)
n s e
creates a new array with the elements that returned true when
e l ice
l
the callback function was applied. rab e
a n sf
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks callback checks whether at least one of the elements in the array meets a certain
The some
u
V that is defined in the callback. The callback function must return a Boolean value.
condition
l a n
Mi Is someone over 18 years old?
var some18yo = persons.some(function(person){
return person.age>18;
});

The filter function creates a new array with the elements that meet the condition defined in
the callback function.
Create an array only with person objects that are over 18 years old:
var grownUps = persons.filter(function(person){
return person.age>18;
});

JavaScript and HTML5: Develop Web Applications 8 - 17


JavaScript Array Extended API

• Array.map(callback)
function callback(value, index, array) creates a
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

new array with the results of the callback when it is called in


each of the elements of the array.

• Array.reduce(callback)
function callback(previousValue,
n s e
currentValue, index, array) applies the callback lice
function for each element in the array, and returns a single
a b le
s
value based on the accumulated result of the callback f
callback.
er
an - tr
o n
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksmethod converts an array of objects to another type; you can use it to extract data
The map
u
V elements or to convert objects.
from
l a n
Mi To get an array of ages:
var ages = persons.map(function(person){
return person.age;
});
The reduce method creates a single value from the entire array.
To sum all the ages:
var totalAge = ages.reduce(function(prevValue, currValue){
{
return prevValue+currValue;
}, 0);

JavaScript and HTML5: Develop Web Applications 8 - 18


JavaScript Array Method Chaining

You can chain invocations on some array methods.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var value = array.filter(filterCallback)


.map(mapCallback)
.reduce(reduceCallback, initialValue);
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s ages of all the grownUps in the persons array in a “single line” by using method
To addkthe
V u
anchains:
Mil var ggrownUpAgeTotal
p g = p
persons.filter(function(person){
( (p ){
return person.age>18;
})
.map(function(person){
return person.age;
})
.reduce(function(prevValue,
reduce(function(prevValue currValue){
return prevValue+currValue;
}, 0);

JavaScript and HTML5: Develop Web Applications 8 - 19


Example: Array Extended API

Use the JSConsole web application and run the following


example to see how to use the Array Extended API.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
o n -tr
s an
Try this in
) h a deฺ
Array i
ฺrs t GuExtended API
JSConsole. s
em uden
Array API with callbacks

a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 20


Exercise

Use the JSConsole and try to complete the exercise


• Array Extended API
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 15 minutes

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
h a dAPI
Exercise: Array Extended
) i eฺ
ฺrs t Gu
Use array functions to filter, map, and reduce.
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks browser, go to the JSConsole application, and run the exercise.
Open your
u
V the required JavaScript code to make the tests pass.
l a n
Add
Mi You can find more help on how to solve a particular test by clicking the result
result.

JavaScript and HTML5: Develop Web Applications 8 - 21


Function Scope
function
f ti x(){
(){
Variable can be resolved because it
var name="john";
is declared in an outer function.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function y(){
console.log(name);
}
}

function outer() { n s e
var x = "I am declared in the outer function"; lice
a b le
function inner() {
Prints the contentsof f exr
console log( )
console.log(x);
- t r an
}
n o n
inner();
s a
}; ) h a
i d eฺ
outer(); sฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Inner Functions
u
V
i l anBecause a function can be inside other functions, an inner function has access to the
M parameters and variables of the function in which it is nested. This is shown in the code in the
slide.
When using callbacks, you will have access to all the variables of any outer scope.
This applies to functions too. You have access to all the variables in any outer function, all the
way to “no function” or global scope.
Every time you declare a new function, you have a new scope.

JavaScript and HTML5: Develop Web Applications 8 - 22


Function Scope and this Reference

• this and that:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var myObj = {
myVar : "Hello there!",
greet: function () {
g
that = this;
innerGreet = function() {
console.log(that.myVar); n s e
ice
};
b l el
innerGreet();
fe r a
}
a n s
}; n - tr
o
myObj.greet();
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
this Keyword
u
V to the fact that the reference to an object is lost within the inner function (innerGreet is
l a n
Due
Mi the inner function in the example) of a function as a method (greet is the function as a method in the example), it is a common practice to save the this reference in a variable
(that, self, or _this, and so on) before using it in the inner function. Otherwise, the use of
this in the inner function would reference the global object or undefined, and not the this
value of the outer function.

JavaScript and HTML5: Develop Web Applications 8 - 23


Overriding Variables

You can override variables by declaring them again in inner


scopes.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var name = "Ed";


function x(){
var name = "John";
n s e
console.log(name);
ice
} b l el
fe r a
console log(name); // Ed
console.log(name);
a n s
n - tr
x(); //John o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
If you re-declare a variable in any inner scope, you will create a new variable with the same
u
V and you will not have access to the outer variable.
name
l a n
Mi

JavaScript and HTML5: Develop Web Applications 8 - 24


Scopes and Variables

var name = "Ed";


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function x(){
console.log(name);
}
x(); // Ed
name = "John";
n s e
x(); // John ice
b l el
var name = "Peter";
fe r a
x();
() // PPeter
t a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
After itkissdeclared in a scope, re-declaring a variable will have no effect, and will work like a
V u value assignment.
simple
an
Mil

JavaScript and HTML5: Develop Web Applications 8 - 25


Closures

• A function inside another function is called a closure.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function add(number1, number2){


function doAdd(){
return number1 + number2;
}
n s e
return doAdd(); ice
b l el
}
fe r a
add(1,1)
dd(1 1) // 2 a n s
- tr
• A closure has access to outer variables. non
s a
) h a
i d eฺ
• Often callbacks are declared s ฺrsclosures.
as t G u
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks is the way of creating new inner scopes in JavaScript.
A closure
u
anV
Mil

JavaScript and HTML5: Develop Web Applications 8 - 26


Closures and Variables

If outer variables change, your closure variables will change too.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function trickyAdd(number1, number2){


function doAdd(){
return number1 + number2;
}
number1 += 1;
n s e
number2 += 2;
e l ice
return doAdd(); r a bl
} n s fe
n - tra
trickyAdd(1,1) // 5 no a
h a s eฺ
) i d
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Closures have access to outer variables and as such, any change made to them in any outer
u
V
context will alter their value.
an
Mil In the example in the slide, the closure doAdd uses the outer variables. Invoking trickyAdd
invokes the closure but not until it changes the values.
You must be cautious because this creates a false illusion of security in the values due to the
fact that the variables number1 and number2 belong to trickyAdd and they might change
by the time the closure is called.

JavaScript and HTML5: Develop Web Applications 8 - 27


Example: Closures

Use the JSConsole web application and run the following


example to see how to create closures and handle different
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

scopes.

Ti
Time Li
Limit:
it 2 minutes
i t

n s e
ice
b l el
fe r a
a n s
o n -tr
s an
) h a deฺ
Try this in
s ฺ rs t Gui Closures
JSConsole.
@ em uden Review Closures

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example in the slide. You can view or edit the example to
u
Vsome of the JavaScript code discussed in this section.
see
l a n
Mi Look at the Console tab in the JSConsole editor. It will show the output for the JavaScript
code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 28


Private Scope with Closures

• Create a function that creates an object.


• Create inner functions (closures).
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Create the object that uses the defined closures.


function createObject(){
var value=0;
function sum(a,b){return a+b;};
n s e
return {
lice
add2:function(val){return sum(2,val);},rable
add10:function(val){return sum(10,val);},
sum(10 val);} n s fe
n - t ra
increment:function(val){value+=val;},
a no
getValue:function(){return
h a s value;}
eฺ
) i d
} } ฺrs Gu
e ms dent
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Using k a
s and scoping variables, you can create private scopes on certain variables and
closures
V u
functions.
l a n
Mi In the example in the slide, the function creates an object with some methods. The object’s
object s
methods invoke closure of the function and use the variables inside the createObject
function scope.
Scopes can be used to create private functions, variables, and objects. By returning a value,
you can control the access to certain methods.

JavaScript and HTML5: Develop Web Applications 8 - 29


Private Scope with Closures

var object = createObject();


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

object.value; // undefined
object.getValue(); //0
object.increment(5);
object.getValue(); // 5
object.add2(5); // 7
n s e
object.add10(10); //20 ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks in the slide shows how access to the value variable is restricted. There is no way
The code
to V u
actually get it because it is local to the function that is invoked and you get no reference to
l a n
Mi the scope created.

JavaScript and HTML5: Develop Web Applications 8 - 30


Example: Private Scope

Use the JSConsole web application and run the following


example to see how to view the required code to create private
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

scopes in objects.

Ti
Time Li
Limit:
it 2 minutes
i t

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t GuiPrivate Scope
@ em uden Create objects with private functions.

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 31


Returning Functions

Functions can be used to create other functions.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function createIncrementByNumber(number){
return function(x) { return number+x; }
}

var inc = createIncrementByNumber(2);


n s e
inc(3) // 5 ice
b l el
inc(10) //12
fe r a
a n s
n - tr
o
an
var inc2 = createIncrementByNumber(10);
inc2(3) // 13 h s
a deฺ
)
ฺrs t Gui
inc2(10) // 20 s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
Because a
ksyou can have functions as variables, you can also have functions that create other
V u
functions.
l a n
Mi The created function is a closure and thus has access to all the outer variables.

JavaScript and HTML5: Develop Web Applications 8 - 32


Example: Returning Functions

Use the JSConsole web application and run the following


example to see how to create and return functions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t GuiReturning Functions
@ em uden Create functions inside a function.

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 33


Closures and Loops

Using closures with loops can lead to some unexpected bugs.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var functionArray = [];


for(i=0;i<5;i++){
functionArray.push(
function(){console.log(i)});
n s e
}
lice
for(t=0;t<functionArray.length;t++){ a b le
s f er
f
functionArray[t]();
ti A [t]() // always
l i t ran
prints 5!
- t
} non a
h a s eฺ
) i d
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
In the example in this slide, closures are created for each iteration on the loop but they use
u
V
the variable i that is declared in the for loop.
anThe value of i is changed in each iteration and, therefore, invoking closures will result in all of
Mil
them printing the same value.
This is because everything happens in the same scope.

JavaScript and HTML5: Develop Web Applications 8 - 34


Anonymous Functions

An anonymous function is declared and used immediately, and


usually its purpose is to create a new scope.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

(function(){ … }());

You can set a new scope to a variable.


var scope = (function(){ … return
{object:"a"};}()); n s e
ice
b l el
fe r a
Or you can store variable state.
state n s
- tr a
(function(newName){ … }(name)); o n
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksand quick way of creating a new scope is by using an anonymous function. This is a
A simple
u
V that is created and invoked immediately after.
nfunction
a Note the syntax of the invocation in the slide and pay attention to the parentheses and braces.
Mil
The entire statement is enclosed in parentheses and the function is declared just as any other
function; when the braces of the function are closed, open another set of parentheses that
represents the function call.

JavaScript and HTML5: Develop Web Applications 8 - 35


Loops with Anonymous Functions

var functionArray = [];


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

for(i=0;i<5;i++){
(function(number){
functionArray.push(
function(){console.log(number)}
);
n s e
}(i));
lice
} a b le
s f er
f (t 0 t f th t ){ ran
for(t=0;t<functionArray.length;t++){
ti A l
n - t
o
functionArray[t](); // prints 0n to 4
s a
} h a eฺ ) id
ฺ r s u
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
You can use anonymous functions to create new scopes that can store the state of some
u
V
variables by copying them to the newly created scope.
anIn the example in the slide, the closure that is stored in the array is created inside an
Mil
anonymous function.
A new scope is created; the scope declares a new number variable as the argument of the
anonymous function and, each time it is called, a new value of the variable i is copied into the
new scope.
Thus, closures can use the new “copied” values that are stored in the anonymous context.
This works because for each closure, a new scope is created that stores the value of the
variable i in the current iteration.

JavaScript and HTML5: Develop Web Applications 8 - 36


Example: Loops with Closures

Use the JSConsole web application and run the following


example to see how to compare looping closures with and without
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

anonymous functions.

Ti
Time Li
Limit:
it 2 minutes
i t

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t GuiLoops with Closures
@ em uden Looping with closures

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 37


Copying Values

function trickyAdd(number1, number2){


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var doAdd =
(function(newNumber1, newNumber2){
return function(){
return newNumber1 + newNumber2;
}
n s e
}(number1, number2));
lice
number1 += 1; a b le
s f er
number2
b 2 += 2 2;
- t r an
return doAdd(); n on
s a
}
) h a
i d eฺ
trickyAdd(1,1) // 2 s ฺrs t Gu
m e ude n
a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
You can create new scopes by using anonymous functions. To do this, copy the values of the
u
V
outer scopes and retain the values that these variables had when the anonymous function
an
Mil was invoked.

JavaScript and HTML5: Develop Web Applications 8 - 38


JavaScript Module Pattern

Modules are independent pieces of code that run in their own


scope. You use anonymous functions to accomplish this.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

(function(){
//
// your module code goes here.
n s e
//
ice
}()); //immediate invocation of the code. b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks functions create new isolated scopes that can effectively copy variables from
Anonymous
u
V scopes, keeping their values when the function is invoked.
outer
l a n
Mi Using these functions, you can create code that can declare any variable or function without
risking interference with other code. The code inside the anonymous function runs in its own
scope. It is a module because it can be run in any application without interfering with other
files.

JavaScript and HTML5: Develop Web Applications 8 - 39


Using Modules

You can create objects in the modular code and return the objects
to use the module anywhere.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var module = (function(module) {


module.method = function(){};
module.publicVariable = "a";
n s e
var modulePrivateVariable="b";
ice
return module b l el
fe r a
}(module || {}));
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
When kyoua
s want to keep adding functionality to a module, you can return an object in the
V u
anonymous function and use that same object as parameter.
l a n
Mi Anything that is added to the object inside the anonymous function will be available to the
application for use later while keeping the module code isolated in its own scope.
You can aggregate functions and variables to the returned object even in different files, thus
keeping code independent and organized.
One disadvantage is that because modules are not connected to each other, you can override
functionality in the module object.

JavaScript and HTML5: Develop Web Applications 8 - 40


Example: Modules

Use the JSConsole web application and run the following


example to see how to create modules.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t Gui Modules
@ em uden Module code example

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 41


Topics

• JavaScript Functions
– Functions as Values
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Functions and Variable Scopes


– Modules
• Prototypes
• HTML5 Drag and Drop
• Delays and Intervals n s e
ice
• HTML5 Canvas b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 8 - 42


JavaScript Prototypes

• All objects in JavaScript have a prototype property.


• You can assign an object to a prototype.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• You can chain prototypes.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks are used in JavaScript to simulate inheritance.
Prototypes
u
If aVproperty or method is not found in the current object, it is searched for in the prototype of
n
l a
Mi the object. If it is not found, the search continues in the prototypes until the root prototype is
reached.

JavaScript and HTML5: Develop Web Applications 8 - 43


Prototype Functions

You can add functions to an object by using:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function A(){
this.getName = function(){ return "A"; }
};

n s e
With prototypes, use the following syntax: ice
b l el
fe r a
function
f ti A(){}
A(){}; a n s
n - tr
n o
A.prototype.getName=function(){return "A";};
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
an(
ks
Using prototypes, you can also declare functions outside the “constructor” function.
u
V
i l anThe difference between declaring functions inside the constructor and outside it is that
M declaring object functions inside creates a new function reference for each object that is
created.
Using the prototype, the function is associated with the constructor and all the objects that are
created. This happens only once and the function is effectively reused in all instances.

JavaScript and HTML5: Develop Web Applications 8 - 44


Prototype Dynamic Object Modification

Adding properties and methods to the prototype will affect all


instances.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function A(){};
var inst1 = new A();
var inst2 = new A();
n s e
A.prototype.getName=function(){return "A";};
lice
console.log(inst1.getName()); // A a b le
s f er
console log(inst2 getName()); // A
console.log(inst2.getName()); n a
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
By using prototypes with objects, you can declare methods that will take effect even in
u
V
existing objects that were created before the function declaration.
anBe careful because invoking the method before it is declared will cause it to fail. For instance:
Mil
function A(){};
var inst1 = new A();
console.log(inst1.getName()); // Error, function is not defined.
A.prototype.getName=function(){return "A";};
This invocation will fail with an error. Therefore, declare the prototype functions immediately
after the constructor function.

JavaScript and HTML5: Develop Web Applications 8 - 45


Prototype Chain

function A(){};
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

A.prototype.getName = function(){
return "proto A"
};
function B(){};
B.prototype = new A();
n s e
var b = new B(); ice
b l el
console.log(b.getName()); // proto A
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks simulates object inheritance by using prototypes.
JavaScript
u
V can assign an object to another object’s prototype.
l a n
You
Mi JavaScript will make a simple lookup when you try to access a property from an object
object.
If the method is not found in the object, it will be searched in the object’s prototype object, and
if this object has a prototype property, the search will continue down the prototype chain
until the root object is found.

JavaScript and HTML5: Develop Web Applications 8 - 46


Example: Prototypes

Use the JSConsole web application and run the following


example to see how to create, use, and assign prototypes to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

objects.

Ti
Time Li
Limit:
it 2 minutes
i t

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t Gui Prototypes
@ em uden JavaScript Prototype Inheritance

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 47


Topics

• JavaScript Functions
– Functions as Values
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Functions and Variable


Scopes
– Modules
• Prototypes
• HTML5 Drag and Drop n s e
ice
• Delays and Intervals
b l el
• HTML5 Canvas fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 8 - 48


HTML 5 Drag and Drop

Drag-and-drop interactions are included in HTML5 by using


JavaScript events.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

In a drag-and-drop operation, usually two elements interact.

The dragged content is stored in a


dataTransfer object. Using n s e
ice
dataTransfer, multiple elements can react
b l el
to drag-and-drop operations. fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks operations are meant to transfer information from one element to another.
Drag-and-drop
V u
i l a n
Commonly, applications share this information by using an intermediate object that serves as
M a means of communication for both elements.
Think of the drag-and-drop as a copy-and-paste operation. In a copy-and-paste operation,
when you copy data, it is stored in the clipboard so that any other object can access the data
and perform a paste.
In a drag-and-drop operation, the dataTransfer object is equivalent to the clipboard of a
copy-and-paste operation.

JavaScript and HTML5: Develop Web Applications 8 - 49


The Drag-and-Drop Process

dragstart(event)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

dragover(event)

n s e
drop(event) ice
b l el
fe r a
a n s
event.dataTransfer
n - tr
o
s an
) h a deฺ
setData(type,
s ฺ G ui
rsgetData(type)
data)
e m dent
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks operations consist of three different events:
Drag-and-drop
u
•V dragstart(event): The drag event sets the dataTransfer object.
l a n
Mi • dragover(event): It reads the dataTransfer object to allow drop on the element.
element
• drop(event): The element reads and uses the dataTransfer object.
The dataTransfer object is accessible by using event.dataTransfer.
Data can be stored in the dataTransfer object by using the setData(type, data)
method. Data can be retrieved from the dataTransfer object by using the
getData(type) method.

JavaScript and HTML5: Develop Web Applications 8 - 50


Drag Start

The HTML elements that can be dragged to add the following


event and set the draggable attribute to true include:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<div ondragstart="drag(event)"
d
draggable="true">Drag
bl Me!</div>
/di

The JavaScript code for the handler sets dataTransfer: n s e


ice
b l el
fe r a
function drag(event) { n s
event.dataTransfer.setData("Text",on -tra
"Dragged");
} s an
a ฺ h de
r s ) u i
m sฺ nt G
@ e ude
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The slide shows in bold the HTML5 attributes that you must add to make an element
u
V
draggable and to trigger a JavaScript function when a drag occurs.
an
Mil The JavaScript function must set the dragged value in the dataTransfer property of the
event object by using the setData method.

JavaScript and HTML5: Develop Web Applications 8 - 51


Drag Over

The elements that may receive drags and drops need to add the
following event:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<div ondragover="dragOver(event)">
DROP HERE!</div>
The JavaScript code is as follows:
function dragOver(event) {
n s e
event.preventDefault();
ice
} b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
The code a
s in bold in the slide shows what you need to add to the elements that can receive a
u
V The JavaScript function must invoke event.preventDefault(); to allow the drop.
drop.
l a n
Mi This event happens when the mouse button is still pressed and the cursor is hovering over
the element. It may happen multiple times as the cursor moves over the element. It is used
usually to provide some feedback to the user.
Note that the dataTransfer object might not be available inside the event variable. It is
platform and browser dependent.

JavaScript and HTML5: Develop Web Applications 8 - 52


Drop

Elements that receive the drops must add the following listener in
addition to onDragOver.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<div ondrop="drop(event)"
ondragover="dragOver(event)"> DROP HERE!</div>

The JavaScript code is as follows:


function drop(event) { n s e
lice
event.preventDefault();
a b le
alert(event.dataTransfer.getData( Text
alert(event.dataTransfer.getData("Text")); s f er
));
- t r an
} on
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The code in bold in the slide shows the code that you must add to an element, which after
u
V
accepting “drops” by using the ondragover event executes a function when the dragged
an
Mil element is released on the target element.
The drop event will trigger and the JavaScript code is executed. You usually read the
dataTransfer property by using the getData method to handle the drop.

JavaScript and HTML5: Develop Web Applications 8 - 53


Example: Drag-and-Drop

Use the JSConsole web application and run the following


example to see how to create drag-and-drop operations with
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

HTML5 and JavaScript.

Ti
Time Li
Limit:
it 2 minutes
i t

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t GuiDrag and Drop
@ em uden HTML5 Drag and Drop JavaScript Events

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 54


Topics

• JavaScript Functions
– Functions as Values
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Functions and Variable Scopes


– Modules
• Prototypes
• HTML5 Drag and Drop
• Delays and Intervals n s e
ice
• HTML5 Canvas b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 8 - 55


Delayed Functions

To execute a function after a set period of time, use:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

timeoutId = setTimeout(function, delay)


Execute the function after delay milliseconds.
Note that setTimeout is not a blocking call.

setTimeout(
n s e
function(){console.log("TIMEOUT!");}
lice
,1000); a b le
s f er
n -t
console.log("After
l l ("Aft ti
timeout!");
t!") ran
n o
This will print “After timeout!” and a second s a
) h a later,d eฺ it will print
“TIMEOUT!” ฺrs t Gu i
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks or timeout function is executed after a certain time.
A delayed
u
Vmost important part is that the setTimeout function does not block the code until the
l a n
The
Mi timeout is met; instead it sets the timeout to occur at some point in the future and the code
continues to execute.
In the example in the slide, the output is:
After timeout!
TIMEOUT!
You can create complex effects by using the timeout combined with mouse events.
You can also simulate multithreaded code by using timeouts.

JavaScript and HTML5: Develop Web Applications 8 - 56


Interval Functions

To execute a function periodically in fixed intervals, use:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

intervalId = setInterval(function, delay);


This will execute the function every delay milliseconds until it is
canceled.
setInterval is not a blocking call.
setInterval(
n s e
ice
function(){console.log("INTERVAL!");}
e l
,1000);
r a bl
e
tra
console log("After interval!");
console.log("After nsf
n -
a no
This will print “After interval!” and then every a s second
ฺ thereafter it
h d e
will print “INTERVAL!”
s ฺrs) t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
s a
Intervalkfunctions are similar to timeouts because the callback function is executed at a point
in V u
the future. But the difference is that intervals are executed periodically until they are
l a n
Mi canceled.
Intervals are useful because the callback is executed in a fixed period of time.
You can create animations by using intervals.

JavaScript and HTML5: Develop Web Applications 8 - 57


Canceling Intervals and Timeouts

You can cancel intervals and timeouts.


Both setInterval and setTimeout return an ID that you can
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

use.

clearTimeout(timeoutId);

n s e
clearInterval(intervalId);
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksand timeouts can be cancelled.
Intervals
u
•V Canceling an interval is the only way to stop its execution.
l a n
Mi • Canceling a timeout will prevent its execution if it has not been executed yet.
yet
When you create a timeout or an interval by using the setTimeout or setInterval
functions, you get a number ID as a result of the invocation. You use this ID number to cancel
intervals or timeouts.

JavaScript and HTML5: Develop Web Applications 8 - 58


Example: Timeouts and Intervals

Use the JSConsole web application and run the following


example to see how to create timeout and interval functions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t GuiTimeouts and Intervals
@ em uden Timeout and interval functions

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 59


JavaScript Concurrency

• JavaScript is not multi-threaded. Every function is executed


sequentially.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• You can simulate concurrency by using intervals and timeouts


but it is not recommended.
• JavaScript
J S i t does
d nott provide
id direct
di t th
thread-control
d t l mechanisms
h i
because there are no blocking calls.
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksJavaScript is not multi-threaded by nature.
Note that
u
V have only one thread when running scripts on a page and usually the page is
l a n
You
Mi unresponsive if a script takes too long to complete.
In fact, if you try to wait for a second, by using the following code, you block the user interface
until the code finishes executing:
var startTime=new Date().getTime();
var currentTime=new Date().getTime();
while((currentTime-startTime)>1000){
currentTime new Date().getTime();
currentTime=new Date() getTime();
}
Instead, think of the task that you want to perform after the second task is completed and use
a timeout.

JavaScript and HTML5: Develop Web Applications 8 - 60


JavaScript Workers

In HTML5, workers are introduced to perform processing without


blocking the UI.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Workers execute a separate js file.


• Workers communicate by using messages.
• Workers cannot manipulate DOM.
• Workers cannot access the window, document, or parent
object. n s e
e l ice
• Workers are executed on a separate system thread. bl
fe r a
Although the workers are on different threads and JavaScript
n s
-
does not provide thread-safety mechanisms, scenarios
n tra where you
might have concurrency problems are scarce
o
nbecause of the
s a
a ฺ
sandboxed environment of workers. ) h ide
ฺrs t Gu
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
JavaScript workers solve the problem of multi-threaded code by executing independent
u
V
JavaScript files. Workers execute a JavaScript file and communicate with the main JavaScript
an
Mil thread by using messages.

JavaScript and HTML5: Develop Web Applications 8 - 61


Using Workers

To create a new worker:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var worker = new Worker("worker.js");

To listen to worker messages:

n s e
worker.onmessage=function(event){
lice
console.log("message from worker"+event.data); a b le
s f er
n -t
}; ran
o
s an
To start the worker (and send messages
) h i d eฺ
a to workers):
worker.postMessage(""); s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
Workersk a
sare really simple to use. You just need to load the JavaScript file. The worker will run
in V u
the Worker object constructor. From there, you just add the onmessage listener to the
l a n
Mi worker to receive messages from the worker.
To send messages to the worker, use the postMessage method in the worker.
You can use workers in the following instances:
• With XMLHttpRequest (shown in the lesson titled “AJAX and WebSocket”)
• For creating timeouts and intervals
• For clearing timeouts and intervals
• For getting the location object (read
(read-only)
only)
• For spawning other workers
Workers cannot access or modify DOM elements, including the window, document, and
parent objects.

JavaScript and HTML5: Develop Web Applications 8 - 62


Example: Workers

Use the JSConsole web application and run the following


example to see how to create workers.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 2 minutes

n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t GuiWorkers
em uden
JavaScript Workers

a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.

JavaScript and HTML5: Develop Web Applications 8 - 63


Topics

• JavaScript Functions
– Functions as Values
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Functions and Variable Scopes


– Modules
• Prototypes
• HTML5 Drag and Drop
• Delays and Intervals n s e
ice
• HTML5 Canvas b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 8 - 64


HTML5 Canvas

HTML5 introduces a canvas element that is used to paint


anything by using JavaScript.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<canvas width="300" height="200"


id h l
id="html5canvas">Canvas is
i not
supported.</canvas>
n s e
ice
If canvas is not supported, the body of the
b l el
canvas element is rendered. fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks canvas element is a blank placeholder with a defined width and height. It is
The HTML5
u
V rendered as a white or transparent block on your page.
usually
l a n
Mi This element can be painted on freely by using JavaScript. You can paint lines, curves, arcs,
rectangles, and images.
The canvas element is a very flexible HTML5 component that lets you draw anything on the
screen by using JavaScript.
One example of a canvas is the game area of an HTML5 game. The game is rendered on the
canvas by using JavaScript.
Other uses might include overlays on the page. Because the canvas can be transparent, you
can use it to paint information on top of your page, similar to tutorials or even animations.
Canvas is a very fast and powerful element. You can create animations by painting different
images on the canvas by using JavaScript. The speed of animation can be controlled by
using intervals.

JavaScript and HTML5: Develop Web Applications 8 - 65


Painting the Canvas

Use JavaScript to paint the canvas element.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var canvasElement =
document.getElementById("html5canvas");
// use the context to paint.
var ctx = canvas.getContext("2d");
n s e
// Set the fill color with any css3 color.
lice
ctx.fillStyle = "#33DD33" a b le
s f er
//fill a rectangle
rectangle.
- t r an
ctx.fillRect(x,y, width, height); on
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
To paint the canvas, you must get the canvas element. Then you get the 2d context from the
u
V
canvas element by calling the .getContext("2d") method. Using the context, you paint on
an
Mil the canvas.
The context is a stateful object where operations change the state of the context, thus altering
any subsequent operation.
For example, you can change the fillStyle of the context. This changes the fill that is used
when painting figures. All figures painted after this change will have the same fillStyle. If you
want to change it or clear it, you just change the fillStyle again.
To paint lines and curves, you must move the cursor on the canvas. All movement operations
will alter the state of the canvas. This is discussed in the following slides.

JavaScript and HTML5: Develop Web Applications 8 - 66


Canvas Space

Most paint functions work on the canvas by providing coordinates.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<canvas width="300" height="200"


(0,0) id="html5canvas"></canvas>

canvas.height
(40,40) (200) n s e
ice
b l el
fe r a
a n s
o n -tr
(150,100)
s an
) h a deฺ
canvas.width sฺrs G ui
(300) e m dent (300,200)

a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksoperations on the canvas work on the canvas space. The canvas space is the
All paint
V u
ncoordinate system that is used to locate dots to paint lines and figures.
a It is a very simple system where the top left corner refers to coordinates (0,0) and the bottom
Mil
right corner refers to the width and height of the canvas. The coordinates are in pixels.
In the example in the slide, you can see different dots on the canvas. The canvas has a width
of 300 and a height of 200.
You can use a bigger or smaller canvas if you need. Just keep in mind that the maximum
values of X and Y will change.
You can paint outside the canvas boundaries but only the area displayed inside the canvas
will be displayed. You might want to do this if you want to start a figure outside the canvas.
For example, painting a circle outside in coordinates (-10, -10) with a radius of 30 will result in
an arc painted on the top left corner of the canvas.

JavaScript and HTML5: Develop Web Applications 8 - 67


Canvas Strokes

You can set styles for the stroke and the fill of figures painted on
the canvas.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Strokes:
ctx.strokeStyle="#000000";

Set line width and cap:


n s e
ctx.lineWidth=3;
ice
ctx.lineCap="butt" | "round" | "square" b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
When k a
s on the canvas, you have two properties for painting lines and figures.
painting
u
V and Fill
l a n
Stroke
Mi The stroke is the line style
style. You can set the color of the line by setting the strokeStyle
property of the context object. You can use any CSS3 color in the format: #000000 or
rgba(r,g,b,a). The rgba notation defines the color components and a transparency value.
Color components are numeric values that range from 0 (no color) to 255 (full color). They
are: r:red, g:green, and b:blue. The transparency component is a decimal numeric value that
ranges from 0 (transparent) to 1 (solid).
Too set tthe
e line
e width,
dt , change
c a ge tthe
e lineWidth
e dt p property
ope ty o
of tthe
e co
context
te t object
object.
To change the way lines are capped, change the lineCap property of the context object.
You can look at the example in the slide to see the different line caps and to get a quick
reference on how to change the stroke style and line width.

JavaScript and HTML5: Develop Web Applications 8 - 68


Canvas Fills

Solid Color:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

ctx.fillStyle="#FF0000";

ctx.fillStyle="rgba(0,0,0,0.3)";

Gradient:
n s e
var grd=ctx.createLinearGradient(x1,y1,x2,y2);
lice
grd.addColorStop(0,"#000000"); a b le
s f er
grd.addColorStop(0.30,
d ddC l St (0 30 "#33AA33")
"#33AA33");
- t r an
grd.addColorStop(1, "#FFFFFF"); non
s a
ctx.fillStyle=grd; h a eฺ ) id
ฺ r s u
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The fillStyle property is very similar to strokeStyle. You can use any CSS3 color or a
u
V
gradient fill.
anGradient fills are more complicated. To use a gradient, you perform the following:
Mil
• Create a gradient object by using the createLinearGradient method in the context
object. This method takes four arguments, which define a line. The line defines the
direction, and the start and end points of the gradient.
• Add one or more color stop to the gradient. This will add the color that the gradient will
use. The first parameter is the location of the color. The value can range from 0 to 1 with
any decimal value for mid points. The second parameter is the color to use, which can
be any CSS3
CSS color.
• Finally set the gradient object to the fillStyle property of the context object.
For more information, visit: http://www.html5canvastutorials.com/tutorials/html5-canvas-
patterns-tutorial/.

JavaScript and HTML5: Develop Web Applications 8 - 69


Canvas Text

You can paint text in a canvas by using:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

ctx.fillStyle="#000000";

ctx.font="12px Arial";
ctx.fillText("HELLO!", 10,10);

n s e
ice
b l el
HELLO!
O fe r a
a n s
(10,10) n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Text onks a
canvas is really simple. Just call the fillText(TEXT, x, y) method on the context
u
V and the text is drawn at the coordinate given. This coordinate is the bottom left corner
object
l a n
Mi of the text box.
Text will use the current fill style and font can be set by modifying the font property of the
context object.

JavaScript and HTML5: Develop Web Applications 8 - 70


Paths and Strokes

You can create paths to paint complex figures.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

ctx.beginPath(); //start a path.


// Path instructions.
ctx.fill(); // Fill the path.
ctx.stroke(); //Stroke the path.
n s e
li ce
When using paths, think of how you would move through the b l e
e r a
shape Use the “movement”
shape. movement instructions to draw a shape shape.
a n sf
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks the most complex figures you can paint by using the canvas. They are composed of
Paths are
u
V lines and movements that together form a figure.
multiple
l a n
Mi To start a path, you use the beginPath method in the context object. When you have completed, you can call the fill and stroke methods in the context object.
• The fill method will fill the figure by using the current fill style.
• The stroke method will draw all the lines and curves of the path by using the current
stroke style.
To start another path, just call the beginPath method. If you forget to call beginPath, with
each new figure,
g , the figures
g will be connected and you
y might
g get
g abnormal effects.
When drawing paths, you will move along the canvas by using the lineTo, moveTo, or curve
methods of the context object. Each line that you draw is connected with your previous
movement.
The following slide demonstrates how to paint by using the canvas and paths.

JavaScript and HTML5: Develop Web Applications 8 - 71


Drawing Paths with Lines
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• ctx.beginPath();
• ctx.moveTo(10, 110);
• ctx.lineTo(60, 10);
• ctx.lineTo(110,110);
• ctx.lineTo(10, 110);
• fill();
• stroke(); e
n s
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
When k a
s paths, you must move a virtual cursor on the canvas to paint lines. Think of this
using
u
V cursor as a pen. In this example, you draw a triangle by using three lines.
virtual
l a n
Mi • Begin eg tthee pat
path.
• Then you move the pen to the start point of the figure in the 10, 110 coordinate.
• From there, draw a line to 60, 10.
• Draw another line to 110,110.
• The draw the final line to 10, 110.
• Fill the shape to create a solid triangle.
• Stroke the triangle to add an ooutline.
tline

JavaScript and HTML5: Develop Web Applications 8 - 72


Path Curves

• ctx.quadraticCurveTo(cx,cy,x,y);
Creates a curve by using one control point
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

ctx.moveTo(10,10);
ctx.quadraticCurveTo(30,50,100,10);

• ctx.bezierCurveTo(c1x,c1y,c2x,c2y,x,y);
Creates a curve by using two control points n s e
ice
b l el
ctx.moveTo(210,40); fe r a
ctx.quadraticCurveTo(230,150,280,50, a n s
300,100); n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s the same rules as lines. You start where the cursor was moved last and from
Curveskfollow
u
V the coordinates given will generate a curve. The cursor will end where the curve
there,
l a n
Mi finishes.
There are two types of curves: Quadratic and Bezier.
• A Quadratic curve uses one control point and the destination point.
• The Bezier curve uses two control points and a destination point.
Control points pull the curve towards them. The curve does not move over the control point.
The destination point is the point where the curve ends. The curve touches this point last.
To visualize how the curve will look
look, draw a line from the start point to the end point
point. Locate
the control points. The line will be pulled towards those points as if it was a string of yarn fixed
at the start and end points.

JavaScript and HTML5: Develop Web Applications 8 - 73


Shapes

Rectangles: (x,y)
ctx.strokeRect(x,y,width,height)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

ctx.fillRect(x,y,width,height)
height

width
Arcs (circles):
n s e
Arcs are paths; you need to begin a path, and ce
li
then fill or stroke it. ble
radius
a
ctx.arc(x,y,
( ,y, radius,
, startAngle,
g , endAngle)
g )
(x,y)
n ferπ
s1.5*
To draw a circle, use: n - tra
n π 0
o
a ฺ sa
ctx.arc(x,y,radius,0,2*Math.Pi)
r s ) h
u i de
m sฺ nt G 0.5* π
@ e ude
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
You can
k a
sdraw rectangles directly. Using the strokeRect method in the context object will
u
V the outline of a rectangle by using the current stroke style. Using the fillRect method
draw
l a n
Mi Tothe
in context object will draw a solid rectangle by using the current fill style.
draw circles or add an arc to a path, use the arc method in the context object. Arcs are
another type of line. If you want to create a filled circle, you need to:
• context.beginPath();
• context.arc(x,y,radius,0,2*Math.pi);
• context.fill();
Unlike lines and curves,
curves arcs start at a point calculated by the center of the arc
arc, the radius,
radius
and the start angle. They will not use the previous point where the cursor was.

JavaScript and HTML5: Develop Web Applications 8 - 74


Painting Images

You can paint an image in a canvas by using an <img> element.


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var img=document.getElementById("imgElement");
ctx.drawImage(img, x, y);

(x,y)
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksimages is one of the simplest operations on a canvas. You need a reference to an
Painting
u
V image in the current document. In the example in the slide, there is an HTML
existing
l a n
Mi element:
<img src="apple.png" id="imgElement">
You can then paint the image in the given coordinates directly. If the image has transparency,
it will be painted with the transparency applied.
You can change the size of the image by using:
drawImage(image, x, y, width, height);
Be aware that proportions will not be respected
respected.

JavaScript and HTML5: Develop Web Applications 8 - 75


Example: HTML5 Canvas

Use the JSConsole web application and run the following


example to see how to use the HTML5 canvas with JavaScript.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 7 minutes


HTML5 Canvas Strokes
HTML5 Canvas Examples

n s e
HTML5 Canvas Fills
ice
HTML5 Canvas Examples
b l el
r a
Try this in sfeText
HTML5 Canvas
n
JSConsole. n - tra
HTML5 Canvas Examples

n o
s a HTML5 Canvas Basic Paths
h a de ฺ HTML5 Canvas Examples

r s ) u i
m sฺ nt G HTML5 Canvas Curves
@ e ude HTML5 Canvas Examples

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Open JSConsole and look for the examples shown in the slide. You can view or edit the
u
V
examples to see some of the JavaScript code discussed in this section.
anLook at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
Mil
If you modify a file, click the Run button to update the preview and run the scripts again.
These examples focus on the HTML5 canvas.

JavaScript and HTML5: Develop Web Applications 8 - 76


Where Can I Learn More?

Resource Website
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

ECMA Script http://www.ecmascript.org/

https://developer.mozilla.org/en-
https://developer mozilla org/en
JavaScript Closures
US/docs/Web/JavaScript/Guide/Closures

HTML5 Drag and Drop


http://www.w3.org/TR/2010/WD-html5-
n s e
20101019/dnd.html
ice
HTML5 canvas
http://www.w3.org/TR/2011/WD-html5-20110525/the-
b l el
canvas-element.html
fe r a
a n s
Canvas 2D context -
http://www.w3.org/TR/2dcontext/
n tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 8 - 77


Summary

In this lesson, you should have learned how to:


• Define functions and use them as values
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Create closures with the appropriate variable scopes


• Write JavaScript functions as modules
• Create drag-and-drop
drag and drop interactions with JavaScript
• Create JavaScript timers and delays to create animations in
HTML
n s e
• Paint on the HTML5 canvas by using JavaScript lice
le b
f e ra
n s
n - tra
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 8 - 78


Practice 8: Overview

This practice covers the following topics:


• Practice 8-1: Creating a New Application with a Canvas and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Painting a Circle with a Button


• Practice 8-2: Using Intervals to Paint Random Circles on the
Canvas
• Practice 8-3: Implementing Drag-and-Drop to Paint Stickers
on the Canvas n s e
• Practice 8-4: Implementing Mouse Gestures to Paint on the e l ice
Canvas with the Mouse r a bl
fe s
- t r an
no n
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 8 - 79


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Mil
an V u
ksa
n(
an ฺ v
mil to u
s
s
a n @
uk e thi s S t
s
)
em uden
h s
ฺrs t Gui
an
o
a deฺ
trn -
a n s fe
r
a b l el
i
ce n s e
9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

AJAX and WebSocket ice n s e


b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
s an Day

) h a deฺ
s ฺrs t Gui Hands-On Practice

@ em uden Lecture

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9-2


Objectives

After completing this lesson, you should be able to:


• Use AJAX with JavaScript to request data from an Application
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Server
• Use AJAX to consume RESTful Web Services
• Use AJAX calls to create
“server push” interactions
• Identify alternatives to AJAX used n s e
in legacy code e l ice
r a bl
• Use WebSocket to create real-time client/server sfe
interactions - t r an
n o n
• Identify the required back-end technologies
a for
a s ฺ
REST and WebSocket with Java)EE7 h ide
ฺrs t Gu
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 9-3


Topics

• Dynamic Data with JavaScript


• Asynchronous JavaScript and XML (AJAX)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Representational State Transfer (REST)


• AJAX Security
• WebSocket
• The Java EE 7 Environment
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9-4


Topics

• Dynamic Data with JavaScript


• Asynchronous JavaScript and XML (AJAX)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Representational State Transfer (REST)


• AJAX Security
• WebSocket
• The Java EE 7 Environment
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9-5


Dynamic Data with JavaScript

JavaScript gets dynamic data from Application Servers.


• JavaScript makes an HTTP request to a server.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• The server processes the request and responds.


• JavaScript receives and processes the response.

Process
n s e
Web Browser
ice
Request
b l el
Web Page
fe r a
a n s
JavaScript
o n -tr
s an
) h a deฺ
ฺrs t Gui
Response
s
@ em uden Application Server
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
a
ks you can create HTTP requests to obtain data from the server.
In JavaScript,
u
V a page loads and scripts run, you can modify the Document Object Model (DOM) with
nAfter
a JavaScript by reacting to events and running timeouts or intervals.
Mil
JavaScript can create HTTP requests that pull information from the server.
The flow of the request/response cycle is the same as when a page loads (see the lesson
titled “Web Application Essentials”) but by using JavaScript, you can make requests at any
given time, and even make multiple requests at the same time.

JavaScript and HTML5: Develop Web Applications 9-6


The Request

JavaScript makes HTTP requests. You construct this with the


following information:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• The address and port of the server


• The URL of the resource
• The HTTP method to use
• The body of the request if needed
n s e
• HTTP headers if needed ce
Request el i
a b l
fe r
a n s
JavaScript
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden Application Server
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ksa request in JavaScript, you need the following information:
To make
u
an •V The complete URL of the resource that you want from the server, for example:
Mil http://ajaxrocks.net/users
ttp //aja oc s et/use s
• The HTTP method that you want to execute. So far you have been using GET and POST
but with JavaScript, you can use all the HTTP methods that are available. This is further
discussed in the REST section of this lesson.
• The body of the request. You use the body to send information to the server, such as
form data, a JSON object, an XML document, and so on.
• HTTP headers. The HTTP headers usually contain useful information about the request,
such as identification information and user credentials.

JavaScript and HTML5: Develop Web Applications 9-7


Server Side Processing

The server receives the request and processes it. The requests
may include:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Database access
• Data processing
• Data filtering
• User authentication
Process
n s e
ice
Request
b l el
fe r a
a n s
JavaScript
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden Application Server
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks receives requests, and processes them to get the required information, or
The server
u
V any operation requested.
executes
l a n
Mi The server usually provides special URLs for JavaScript services that return
JavaScript Object Notation (JSON) strings that can be parsed and the resulting object
processed in your JavaScript code.
Server-side processing takes care of the bulk of operations required to generate data for your
application.
This server side component is usually deployed on application servers and enterprise
applications are programmed with a more robust and complete set of technologies such as
Java EE.

JavaScript and HTML5: Develop Web Applications 9-8


Response

The server will send a response with data.


A callback in JavaScript will process the response. It can:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Create HTML elements to display data


• Modify DOM elements
• Start timeouts, intervals, or workers to process data
• Make another request for further Process
n s e
information ce
Request el i
a b l
fe r
a n s
JavaScript
o n -tr
s an
) h a deฺ
ฺrs t Gui
Response
s
@ em uden Application Server
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks assembles a response, and sends it back to your application.
The server
V u
i l a n
A response contains a status code that is very useful in verifying the result of the server
M invocation. A status of 200 would mean that the operation was successful; a 404 would mean
that a nonexistent resource was requested; and a 500 would mean that something went
wrong on the server.
In the body of the response, you will find the response information, usually in JSON or XML
format, which you can parse to JavaScript objects to be used in your application and shown to
the user.

JavaScript and HTML5: Develop Web Applications 9-9


Topics

• Dynamic Data with JavaScript


• Asynchronous JavaScript and XML (AJAX)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Representational State Transfer (REST)


• AJAX Security
• WebSocket
• The Java EE 7 environment
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9 - 10


Asynchronous JavaScript and XML

Asynchronous JavaScript and XML (AJAX) is the API used to


create HTTP requests to servers.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var xmlhttp = new XMLHttpRequest();


xmlhttp.open(Method, URI, Async);
xmlhttp.onload = function() {};
n s e
xmlhttp.send(requestBody);
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks HTTP requests, you use the XMLHttpRequest object, which is the core of AJAX.
To create
u
an •V As you can see in the code in the slide, you provide the HTTP method and the URI of
Mil t e resource
the esou ce to ope
open a request.
equest
• You add a callback function to the XMLHttpRequest object to handle the response
when it is received from the server.
• Finally, you call the send method with the body of the request (can be omitted in the
call).
Note: The onload callback is implemented by most modern browsers. It is a convenient
callback that is invoked when the request is completed, but if y
you need a more compatible
and extensible callback use the onreadystatechange callback instead. If you use
onreadystatechange, you will need to check the status of the request.

JavaScript and HTML5: Develop Web Applications 9 - 11


AJAX and XML

When AJAX was conceived, XML was a primary choice to send


and receive data.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

XML is not required; AJAX is often used with JSON, plain text, or
even partial DOM structures.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks “Asynchronous JavaScript and XML” is not a very accurate representation of what
The name
u
VAPI is really used for.
this
l a n
Mi It was first conceived to make asynchronous calls to servers that returned an XML document
that you could parse, but all this was done on top of the HTTP protocol. In reality, people were
performing simple HTTP calls and soon XML was substituted for JSON or even DOM
elements that could be inserted directly into HTML pages.
Because changing the name to something more meaningful such as HTTPRequest would
mean disregarding backward compatibility, the AJAX acronym and the XMLHttpRequest
object remain.

JavaScript and HTML5: Develop Web Applications 9 - 12


AJAX and Compatibility

As with other JavaScript technologies, AJAX has some


compatibility notes.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

You can implement the following function to create an


XMLHttpRequest object:
function
f ti createAjax(){
t Aj (){
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
n s e
return new XMLHttpRequest(); lice
} else { a b le
s f er
// IE6
IE6, IE5
- t r an
n o n
return new ActiveXObject("Microsoft.XMLHTTP");
}
s a
a ฺ
} )h ide
ฺrs t Gu
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
As part of the history of AJAX in its early stages, not all browsers supported it directly
u
V
(specifically, Internet Explorer 6), thus necessitating another way of constructing the
an
Mil XMLHttpRequest object via ActiveXObjects.
With time, the XMLHttpRequest object became a standard and although IE6 is not as widely
used as when AJAX was created, it is important to know how to create it for these browsers.
Because you will be working with the latest browsers in this course, you will use the
XMLHttpRequest constructor only.

JavaScript and HTML5: Develop Web Applications 9 - 13


Synchronous AJAX

To make a synchronous AJAX call, use:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var xmlhttp = new XMLHttpRequest();


xmlhttp.open(Method, URI, false);
xmlhttp.send(requestBody);
// Handle response here
n s e
// DO NOT add the callback: xmlhttp.onload ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
AJAX can a
s be used synchronously; that is, your code will stop executing when you call the
V u
xmlhttp.send method.
l a n
Mi When the response is received, the code will continue to execute in the statement after the send call.
If you are going to use synchronous AJAX, it is important that you should never add any
callbacks to the xmlhttp object.
Also remember that JavaScript is single-threaded and using synchronous AJAX calls might
make the page unresponsive while the server processes the request.

JavaScript and HTML5: Develop Web Applications 9 - 14


Asynchronous AJAX

To make an asynchronous AJAX call, use:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var xmlhttp = new XMLHttpRequest();


xmlhttp.open(Method, URI, true);
xmlhttp.onload = function() {
// Handle response here. use xmlhttp closure
n s e
};
lice
xmlhttp.send(requestBody); a b le
r e
a n sf
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks AJAX is the preferred way of creating requests.
Asynchronous
u
V create an asynchronous request and after the send method is invoked, the script
l a n
You
Mi continues immediately.
When the response is received from the server, the xmlhttp callbacks are executed.
You should not read the response outside the callbacks because the response might be
empty or partially completed. The only way to know that a response has completed is inside
the callbacks.

JavaScript and HTML5: Develop Web Applications 9 - 15


Handling AJAX Responses

In both synchronous and asynchronous AJAX, handle the


response by using the XMLHttpRequest object:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

if (xmlhttp.readyState === 4) {
// Response is completed.
var responseStatus = xmlhttp.status;
n s e
var data = xmlhttp.responseText;
ice
} b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
s practice in xmlhttp callbacks, you check for the readyState property of the
As a common
k
u
V object to know if the response has completed.
xmlhttp
l a n
Mi The values that xmlhttp.readyState can have are:
• 0: Unsent. The open method has not been called.
• 1: Opened. The open method was called but the send method has not been called.
• 2: Headers received. The request has been made and the server sent back the
response headers.
• 3: Loading. The request is being received and xmlhttp.responseText holds partial
data.
• 4: Done. The response is fully received and xmlhttp.responseText has the entire
response.
Additionally, you can check the xmlhttp.status property to get the HTTP response code.

JavaScript and HTML5: Develop Web Applications 9 - 16


Exercise: AJAX

Use the JSConsole web application and try to complete the


exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Create an AJAX service call by using an asynchronous call


and the onreadystatechange callback to log the entire
AJAX process
process.

Time Limit: 15 minutes n s e


ice
b l el
fe r a
a n s
o n -tr
s an
) h a deฺ
s ฺrs t Gui Exercise: AJAX
@ em uden Create simple AJAX calls.

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9 - 17


Topics

• Dynamic Data with JavaScript


• Asynchronous JavaScript and XML (AJAX)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Representational State Transfer (REST)


• AJAX Security
• WebSocket
• The Java EE 7 Environment
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9 - 18


Representational State Transfer

REST is the architecture that the entire web uses. It is based on


the following design principles:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Client/server interactions
• Uniform interface
• Layered system
• Cache
n s e
• Stateless
e l ice
• Code-on-demand abl fe r
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
REST k a
issa term that has existed for a long time. Roy Fielding describes REST in his doctoral
V u
dissertation at UC Irvine, and defines the web architecture for servicing multiple clients in a
l a n
Mi flexible, scalable, and uniform way.
REST takes full advantage of the HTTP protocol. The complete HTTP protocol complies
entirely with the REST proposed architecture:
• Multiple and diverse clients exist in the form of web browsers and applications.
• Uniform Resource Locators and HTTP methods are present to access and modify
resources.
• It can be a system
y that mayy contain manyy layers
y in between the client and the server.
• Caches can be implemented on resources because often the same operations
performed over the same resources produce the same result.
• Stateless operations establish no sequence or dependency in REST calls.
• Finally, servers may provide code that needs to be executed. Most often, instead of
providing code, the server provides further possible operations in the form of
HyperMedia in such a way that clients know what REST operations are possible.

JavaScript and HTML5: Develop Web Applications 9 - 19


REST on the Web

You are already using REST.


• Client/server interactions: Browser – Web Server
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Uniform interface: HTTP, URL


• Layered System: IP: Proxies, Gateways, and so on
• Cache: Web browser cache, intermediary caches
• Stateless: HTTP request-and-response model
n s e
• Code-on-demand: JavaScript code ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks the most common way of using REST is through AJAX calls.
In JavaScript,
u
anvarV xmlhttp = new XMLHttpRequest();
Mil xmlhttp open(Method URI,
xmlhttp.open(Method, URI true);
xmlhttp.setRequestHeader(header,value);
xmlhttp.onload = function() {};
xmlhttp.send(requestBody);
As you can see, the URI and Method represent the resource to be accessed or modified.
q
Use the request headers to p
provide additional information about the request.
q If needed,, add a
requestBody to provide data in the request.
In JavaScript applications, you need not be concerned about proxies, caches, communication
architecture, and so on.

JavaScript and HTML5: Develop Web Applications 9 - 20


Practical REST

Pressing “enter” executes a “GET”


Address: Uniform Resource Identifier request on the resource.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks in the slide, REST begins in the web browser when you enter an address and
In the example
u
V Enter.
press
l a n
Mi The browser makes an HTTP GET request to get the resource from a server that is specified
by the Uniform Resource Identifier provided in the address bar.
Uniform Resource Identifier or Uniform Resource Locator
• A URI is composed of the name of the resource but does not specify the way to access
such resource.
• A URL has the protocol or way to get a particular resource.
In the end,
end all URLs are also URI but the term URI is more widely accepted when referring to
addresses because sometimes the protocol is omitted, for example:
• http://www.oracle.com/education is a valid URL and URI.
• www.oracle.com/education is a valid URI only.
Thus, using URI for both is correct and more “universal.”

JavaScript and HTML5: Develop Web Applications 9 - 21


Practical REST
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

GET : http://server/resource

n s e
Web ice
b l el
f er a
s
anServer
- t r
/resource

n on
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
The requesta
s is sent through the network to the server, which locates the resources and
u
V the method. In the example in the slide, the method is a GET request. Thus, the server
applies
l a n
Mi will create a representation of the resource and send it back to the client.

JavaScript and HTML5: Develop Web Applications 9 - 22


Practical Rest
GET: http://server/resource
p
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

AppServer

Gateway
DB
Web
n s e
ice
Proxy|cache
b l el
fe r a
a n s
WebServer
n - tr
o
s an
) h a deฺ
s ฺrs t Gui AppServer

@ em uden Servers
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks scenario, multiple layers are involved.
In a real-world
u
an •V The client communicates with the web by using routers, gateways, and other devices.
Mil • There can be proxies that will process the request and redirect it accordingly
accordingly.
• There can be caches that can store some frequent responses. Often, a cache can check
whether a usually “static” response has changed in the server and if it is not the case, a
cached version is sent back. This is possible because of the stateless nature of HTTP.
• The web server may delegate processing to Application Servers to get the information
required to construct a resource or to modify data in a database.
Note that sometimes the WebServer is a module of a bigger Application Server.

JavaScript and HTML5: Develop Web Applications 9 - 23


REST in Action

To use REST in web applications, you need to address the


following:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• The HTTP method that you need


• The resource identified by its URI
• The content of the request and parsing of the response
accordingly
n s e
ice
var xmlhttp = new XMLHttpRequest();
b l el
xmlhttp.open("GET","http://server/resource",true);
fe r a
xmlhttp.setRequestHeader(header,value);
a n s
xmlhttp.onload = function() {};
n - tr
o
an
xmlhttp.send(requestBody);

h s
a deฺ
)
ฺrs t Gui
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Using k a
s in JavaScript involves making one or several AJAX calls.
REST
u
ToV
n know how to use a particular REST service, you need to know what resources you need to
i l a
M access, what methods you can ask for, and what data is going to be exchanged.
The preferred format for the data sent from and to servers is JSON, although the specific
format is service dependent.

JavaScript and HTML5: Develop Web Applications 9 - 24


HTTP Methods

• GET

Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

PUT
• POST
• DELETE

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
a
ks GET method is used to obtain the resource.
• The
u
•V PUT is used to update the resource.
an •
Mil POST is used to add a new resource
resource.
• DELETE is used to remove a resource.
HTTP defines the OPTIONS, HEAD, TRACE, and CONNECT methods as well but their usage in
RESTful APIs is not as wide.
Sometimes, you will find the OPTIONS method returning a representation of the possible uses
of the other methods as well as the URI compositions available. This is not standard and
should not be relied upon.
upon

JavaScript and HTML5: Develop Web Applications 9 - 25


RESTful URI

URIs should describe access to a resource, for instance.


• GET http://www.rest.com/users.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

– Lists all the users


• GET http://www.rest.com/users/john.
– Gives the details of a user identified as “john”
john
• POST http://www.rest.com/users.
– Creates a new user e
n s
• PUT http://www.rest.com/users/john. ice
– Updates the user identified as “john” b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
In the examples in the slide, you can see the common structure of the RESTful API’s URIs.
u
V are usually constructed progressively as you need more details.
l a n
URIs
Mi For an application that stores places and reviews of such places:
• /nearby/places  Refers to the places that are nearby to the user
• /places  Refers to the list of places registered
• /places/toms_pizza  Refers to the place called Tom’s Pizza
• /places/toms_pizza/reviews  Refers to the reviews of the place called Tom’s Pizza
You can see how Methods would apply:
• GET /nearby/places  Gets a list of the nearby places
• POST /places  Adds a new place
• PUT /places/toms_pizza  Updates the place called Tom’s Pizza
• DELETE /places/toms_pizza  Deletes the place called Tom’s Pizza
• DELETE /nearby/places  NOT ALLOWED

JavaScript and HTML5: Develop Web Applications 9 - 26


Example: REST and AJAX

Use the JSConsole web application and run the following


example to see how to use AJAX to invoke REST services.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

This example contains source code that can be added to a


server-side Java EE7 application.

Time Limit: 2 minutes


n s e
ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t Gui REST and AJAX
@ em uden RESTful Services and AJAX

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.
The example contains Java files, which, when added to a Java EE 7 application, will provide
the RESTful services by using JAX-RS 2.0.
This is already deployed in the lab environment.

JavaScript and HTML5: Develop Web Applications 9 - 27


Topics

• Dynamic Data with JavaScript


• Asynchronous JavaScript and XML (AJAX)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Representational State Transfer (REST)


• AJAX Security
• WebSocket
• The Java EE 7 Environment
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9 - 28


AJAX Security Concerns

With AJAX, you can get information that might go into your
applications.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Data should be validated.


• Requests should always refer to known sources.
• Third-party services should be used with care.

e
Security measures should be enforced in your code although the cens
web browser will provide some security against some attacks.l e li
b ra
f e
a ns
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 9 - 29


A Basic AJAX Attack

You need to consume a service from a third party provider that


provides you with the data that you need to display in your
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

application. The application:


• Creates an AJAX request
• Receives
R i th
the response
• Sets the innerHTML of an element with the response data
Can you spot where the problem is? n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks is with data not being validated before it is added to the page.
The problem
u
•V External HTML code can contain <script> elements.
l a n
Mi • The JavaScript code might include malicious code code.

JavaScript and HTML5: Develop Web Applications 9 - 30


JavaScript

Using innerHTML and eval() is extremely unsafe.


An attack is easily executed if:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• The server sends malicious HTML code in the response that


alters your application document
• The server sends a <script> element with malicious code

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
innerHTML a
s replaces the entire contents of an element without validating its structure or
u
V Furthermore, because you can set innerHTML with anything, including HTML
validity.
l a n
Mi elements, scripts, and CSS code, you can add elements that can harm your site.
Also, using innerHTML is worse than adding elements by using DOM operations, because
after you set innerHTML, the browser removes all the children elements, parses the
innerHTML text, creates DOM elements, and adds them to the element.
eval() is inherently dangerous because it executes any JavaScript code.
To avoid problems, never parse JSON by using eval(); use JSON.parse() instead. This
is a known vulnerability that can be easily avoided.

JavaScript and HTML5: Develop Web Applications 9 - 31


Trusted Servers, Untrusted Data

Even if the service is trusted, it can contain data from users that
seek to harm AJAX clients.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• A service provides you access to the latest post in a forum.


• A user includes in the post a <script> element with
malicious
li i code.
d
• Applications that consume the service are at risk of executing
the malicious code. n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
As a rule, a
s validate all external data and verify its structure. If you want to add text to an
u
V use element.appendChild(document.createTextNode(TEXT)); thus, you
element,
l a n
Mi avoid creating unexpected elements and the element will contain plain text only.
If you need to create elements, create them by using document.createElement.
Always have a known structure in the elements that you create. Do not use data from services
as the element name because that can give unwanted control to the service over the layout of
your page.
It is a good practice to always try to validate data and use DOM methods to modify your
pages even if you use your own services.
Remember that even if you create the service and the JavaScript client, the user data might
exploit vulnerabilities in your code. Trust your service but be wary of user data.

JavaScript and HTML5: Develop Web Applications 9 - 32


Security Measures

When consuming third-party services:


• Never use innerHTML or eval()to handle the response
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Try to never use services that provide HTML markup in the


response and favor JSON or XML
• Create all visual elements manually:
document.createElement and
document.createTextNode n s e
• Construct secured URIs for consuming services; do not use lice
a b le
services that provides absolute URIs fer s
- t r an
no n
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 9 - 33


Cross-Site Scripting (XSS)

This happens when you request information from another server


and this sends data that modifies your page or inserts malicious
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

scripts.
Browsers prevent one type of attack by enforcing the “same origin
policy ”
policy.
• A JavaScript file may not make AJAX requests to another
resource that is not in the same server as the JavaScript. s e
e n
You need to verify that you make AJAX requests only to knowne lic
and trusted servers. r a bl
e f
t r a ns
no n-
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Most browsers enforce the “same origin policy” by default and it is a common security feature.
u
V
Although you cannot override the client’s security policies, REST services can provide hints
an
Mil and suggestions in the form of response headers to allow invoking services from a different
“origin.”
Most REST APIs already include the required headers but some browser and security
configurations might restrict them.

JavaScript and HTML5: Develop Web Applications 9 - 34


Topics

• Dynamic Data with JavaScript


• Asynchronous JavaScript and XML (AJAX)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Representational State Transfer (REST)


• AJAX Security
• WebSocket
• The Java EE 7 Environment
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9 - 35


WebSocket

WebSocket is the technology part of the HTML5 specification that


redefines the way clients and servers connect, allowing full-
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

duplex continuous connections.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
s a
BeforekWebSocket, you needed one connection each time you needed to send and receive
u
V from the server. After data was sent and received, the connection was closed.
data
l a n
Mi Because connections in HTTP are always started by the client, if the server needed to send
data to clients, it required an active connection already. A client would establish a connection,
and then the server would delay the response until it had something to send to the client. If
the connection was dropped, the client would open another connection to the server. Using
AJAX for real-time communication has a lot of overhead and unnecessary boilerplate code.

JavaScript and HTML5: Develop Web Applications 9 - 36


HTTP Push Techniques Versus WebSocket

HTTP Push
• HTTP uses simulations to enable server push and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

real-time updates.
• AJAX and Comet rely on polling the server for changes.
• The server may stream changes, delay responses, or perform
a combination of both.
• If a connection is closed, another connection is made. n s e
e l ice
• The client notifies the server as usual by using a separate bl
r a
request.
q sfe n
n - tra
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
The HTTP protocol is limited to a simple request–response case.
u
V
i l anA request will generate one response.
M Pushing data from the server is not possible natively in HTTP
HTTP. However
However, there are ways to
emulate this behavior. Servers delay the response or stream it little by little, so the browser
can handle it progressively.
Sending continuous data from the client to a server implies that multiple requests are being
sent.
AJAX is used to make requests without refreshing the page or by using JavaScript events.
Comet, a streaming technology that uses AJAX
Comet AJAX, streams data from the server that is handled
by JavaScript, emulating the server push.

JavaScript and HTML5: Develop Web Applications 9 - 37


HTTP Push Techniques Versus WebSocket

WebSocket:
• HTTP is used to handshake and initiate the WebSocket
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

connection.
• The connection remains open and works like a full duplex
socket;
k t messages can be
b written
itt to
t it.
it
• There is only one connection for upstream and downstream
communication. n s e
• The connection lasts as long as the client and the server want e l ice
to communicate (no need to reconnect). r a bl
fe s
- t r an
no n
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
WebSocket is a completely new protocol for web server connection. The server can push data
u
V
to the clients at any time. Clients can stream data to the server and send messages any time.
an
Mil Only one HTTP connection is made for both.

JavaScript and HTML5: Develop Web Applications 9 - 38


WebSocket Versus Polling

Server Message Message Message


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Polling

HTTP HTTP HTTP HTTP HTTP HTTP


Request Response Request Response Request Response

Browser

n s e
Server ice
el
Message Message Message Message
l
Socket

HTTP
r a b
HTTP Connection
n s fe
WebS

Request Upgrade
- tr a
o n
Browser Message Messagea n Message
h a s eฺ
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
V uks
an
Mil

JavaScript and HTML5: Develop Web Applications 9 - 39


Implementing WebSocket in JavaScript

1. Connect to the websocket object by using its absolute URI


and the ws: or wss: protocol.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

2. Add an onmessage callback to the websocket object to


handle incoming messages.
3 Send
3. S d messages to t the
th WebSocket
W bS k t server by
b usingi th
the send
d
method in the websocket object.
Note: You can send and receive text strings only by using n s e
ice
WebSocket.
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9 - 40


A WebSocket Example

var socket = new


var socket;
WebSocket("ws://localhost:8080/JSConsole/chatWebSocket");
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

socket = new WebSocket


socket.onmessage = function(event){
("ws://localhost:8080/JSConsole/ws/echoWebSocket");
var chatMessage = event.data;
socket.onmessage = function(event) {
document.getElementById("messages").innerHTML+=
var message = event.data;
event data;
"<b>"+chatMessage+"<br>";
console.log(message);
}; }
socket.onopen = function(event) {
function sendMessage() {
n s e
socket.send("HELLO!");
var messageField = document.getElementById("message"); lice
socket.close();
a b le
socket.send(messageField.value);
}
f e r
messageField.value
Fi ld l = ""
""; an s
- t r
} on
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
WebSocket methods:
u
V
• socket.send(message);  Sends a message to the server
an
Mil socket close()  Closes the connection
• socket.close()
WebSocket callbacks:
• onclose -- function(event)  Called when the WebSocket is closed
• onerror – function(event)  Called when there is an error
• onmessage – function (event)  Called when a message is received from the
server
• onopen – function(event)
f ti ( t)  Called
C ll d when
h the
th WebSocket
W bS k t iis opened
d and
d ready
d tto
send and receive messages
You get the contents of the message by using the event.data property.
Messages are only text strings. A common practice is to send JSON objects as strings.

JavaScript and HTML5: Develop Web Applications 9 - 41


Example: WebSocket

Use the JSConsole web application and run the following


example to see how to create a chat by using WebSocket and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

HTML5.
This example contains source code that can be added to a
server side Java EE7 application.
server-side application

Time Limit: 2 minutes n s e


ice
b l el
fe r a
a n s
Try this in o n -tr
JSConsole.
s an
) h a deฺ
s ฺrs t GuiWebSocket
@ em uden WebSocket Chat

a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
Open JSConsole and look for the example shown in the slide. You can view or edit the
u
V to see some of the JavaScript code discussed in this section.
example
l a n
Mi Look at the Console tab in the JSConsole editor. It shows the output for the JavaScript code.
If you modify a file, click the Run button to update the preview and run the scripts again.
The example contains a Java file, which, when added to a Java EE 7 application, adds the
WebSocket server endpoint to handle the chat.
This is already deployed in the lab environment.

JavaScript and HTML5: Develop Web Applications 9 - 42


When to Use WebSocket and AJAX?

• WebSocket is not a replacement for AJAX or Comet.


• WebSocket is for small, real-time data (notifications and
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

server push).
• WebSocket is for constant client input (like games).
• AJAX is for partial requests, partial page rendering, and
background client requests.
• There are several JavaScript libraries that use AJAX. n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks should complement your application, not substitute your AJAX and Comet
WebSocket
V u
modules.
l a n
Mi WebSocket is bidirectional. If there is a lot of data exchange, you can use it.
WebSocket is fast and almost real time. Use it for notification or server-push problems.
Use AJAX to render portions of the page with user-controlled request, for example, data table
pagination.
JSF includes AJAX components to enable applications to render parts of a page or make
requests without refreshing the page.
WebSocket is a new technology that is not compatible with old browsers
browsers. Remember this
when designing WebSocket services.

JavaScript and HTML5: Develop Web Applications 9 - 43


Topics

• Dynamic Data with JavaScript


• Asynchronous JavaScript and XML (AJAX)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Representational State Transfer (REST)


• AJAX Security
• WebSocket
• The Java EE 7 Environment
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9 - 44


The Java EE 7 Environment

• In AJAX and WebSocket, you use an Application Server to


have access to services.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Java EE 7 provides all the required technologies to build


REST and WebSocket services.

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
The technologies behind the server-side components that you have been using are
V u
developed by using Java EE 7.
l a n
Mi Java EE 7 is an enterprise application development platform. It is a set of technologies
already on a server that allows you to create dynamic and extensible applications.
Java Platform, Enterprise Edition (Java EE) is the standard in community-driven enterprise
software. Java EE is developed by using the Java Community Process, with contributions
from industry experts, commercial and open source organizations, Java User Groups, and
countless individuals. Each release integrates new features that align with industry needs,
improves application portability, and increases developer productivity. Today, Java EE offers
a rich
i h enterprise
t i software
ft platform
l tf with
ith multiple
lti l iimplementations
l t ti tto choose
h ffrom.

JavaScript and HTML5: Develop Web Applications 9 - 45


Java EE 7 Application Server

An Application Server:
• Accesses dynamic data from data sources (databases,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

services, and so on)


• Has business logic to accomplish certain tasks
• Can provide web application data, views (HTML), and logic
(JavaScript)
• Provides multiple ways of accessing n s e
resources and services: REST, lice
a b le
SOA, WebSocket, web pages, and so on fer s
- t r an
no n
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
An Application Server is the server-side implementation of the Java EE 7 specification. You
u
V
develop applications that are deployed on Application Servers, which provide all the Java EE
an
Mil features.
You program Java applications that run on the Java Virtual Machine.
You develop Java EE applications that run on a Java EE Application Server, which runs on a
Java Virtual Machine.
Java EE extends the Java API with all the features needed to write enterprise-level
applications.

JavaScript and HTML5: Develop Web Applications 9 - 46


Java EE 7 Technologies
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks and JSP enable you to create dynamic HTML pages, JavaScript, CSS, and so
• Servlets
u
V on.
an •
Mil JS e
JSF enables
ab es you to ccreate
eate data
data-bound
bou d HTML pages like
e a des
desktop
top app
application.
cat o
• JAX-RS enables you to create RESTful Web Services with ease.
• WebSocket server endpoints enable you to create WebSocket services.

JavaScript and HTML5: Develop Web Applications 9 - 47


Where Can I Learn More?

Resource Website
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

AJAX XmlHttpRequest level http://www.w3.org/TR/2014/WD-XMLHttpRequest-


1 20140130/

REST - semantic Web


http://www.w3.org/2001/sw/wiki/REST
Standards

Web Services Architecture http://www.w3.org/TR/ws-arch/


n s e
ice
The WebSocket API http://www.w3.org/TR/2011/WD-websockets-20110929/ b l el
f e ra
t r a ns
o n -
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
ks a
u
anV
Mil

JavaScript and HTML5: Develop Web Applications 9 - 48


Summary

In this lesson, you should have learned how to:


• Create AJAX calls to get data from an Application Server
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Consume RESTful Web Services by using AJAX


• Use AJAX calls to create “server push” interactions
• Identify alternatives for AJAX
• Create real-time client/server communications with
n s e
WebSocket ce
le li
• Identify the back-end technologies in a b
Java EE 7 required for REST and s f er
WebSocket - t r an
n no
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
u ks
V
an
Mil

JavaScript and HTML5: Develop Web Applications 9 - 49


Practice 9: Overview

This practice covers the following topics:


• Practice 9-1: Creating a New Single Page Application with
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Navigation by Using REST Calls to Get Dynamic Data


• Practice 9-2: Creating a Tic-Tac-Toe Game Client with
W bS k t
WebSocket

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 9 - 50


10
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Developing
D l i A Applications
li ti with
ith
JQuery ice n s e
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved.

an s
n (mil to u
uksa
n V
a
Mil
Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
Day
s an
) h a deฺ
ฺrs t Gui
Hands-On Practice
s
Lecture

@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 2


Objectives

After completing this lesson, you should be able to:


• Add jQuery and jQuery UI libraries to your projects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Use selectors and DOM manipulators to handle


documents
• Handle events with jQuery
• Animate elements and apply
effects in the document n s e
ice
• Handle AJAX server responses b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 3


Topics

• Adding jQuery to Your Project


• Selectors and DOM
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Events
• Animation and Effects
• Ajax
• jQuery UI
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 4


Adding jQuery to Your Project
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<!DOCTYPE html>
<html>
<head>
<title>The Next Big Front-End Conference</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css" />
n s e
<script src="scripts/jquery-1.11.1.js"></script>
lice
<script src="code.js"></script>
a b le
</head>
s f er
<body>
- t r an
</body>
n o n
</html> a s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
jQuerykissa JavaScript library that helps in dealing with common tasks when you are working
V
with uweb pages. With jQuery, you can refer elements in the document and manipulate them
an
Mil by adding content; edit CSS styles; define events handlers; and create animations. It also has
Ajax utilities. jQuery helps you to deal with incompatibilities between browsers because it
includes methods for each browser, without having to write cross-browser JavaScript code.
Using jQuery
To use jQuery, you need to link the file to your web page by using the <script> element in
the HTML page, as shown in the slide. Make sure to include all other JavaScript files after you
include the jQuery library.
You can download and use a local copy that you can get from the jQuery site at
http://jquery.com/ or use a version of the file that is hosted on an external server and is
available through Content Delivery Networks (CDN). The version of the local jQuery file used
in this lesson is 1.11.1.
Licensing
jQuery is open source, under the MIT license. If you need to include jQuery in your projects,
you
o can rere-license
license jQ
jQuery
er under
nder the GNU P Public
blic License
License.

JavaScript and HTML5: Develop Web Applications 10 - 5


Topics

• Adding jQuery to Your Project


• Selectors and DOM
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Events
• Animation and Effects
• Ajax
• jQuery UI
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 6


Selecting DOM Elements

• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$(selector) or jQuery(selector)

• Examples:
$('p'); // select all paragraphs
$('#section-1'); //select the single element with id
$('.advertising'); // select all elements that have this
n s e
// class
lice
$('footer p.user-groups');
a b le
$('h1,h2'); // select all <h1> and <h2>
s f er
$('input[type=text]'); // select input type with
- t r an
on
// attribute type=text
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Because jQuery is focused on queries, you use selectors, or expressions, to identify the target
u
V
elements on a page. You saw previously in the lesson titled “Style Applications Using CSS3
an
Mil and JavaScript,” the power of selectors, which represent elements based on their type,
attributes, or position within the HTML document. jQuery uses the same selectors as CSS3.
The syntax for selecting elements is presented in the first code snippet in the slide. The $()
function accepts a CSS selector and returns a new jQuery object. The dollar sign ($) is an
alias for jQuery, so they can be used interchangeably.
The second code snippet in the slide shows some examples of selections of certain parts of
the document.
jQuery Chains
With jQuery, there is no need to loop over the array of elements. It is possible to select
multiple sets of elements in a single jQuery object and add functions one after the other
chained by a period. Each function operates on the same object.

JavaScript and HTML5: Develop Web Applications 10 - 7


Custom jQuery Selectors

• Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$( "header:has(h1)" );

$( "p:contains('Proin nonummy')" );

$( "p:eq(1)" ); // Select the second paragraph

$( "input:not(:required)" ); // Select all inputs that


n s e
are not required
lice
$("input:file"); ble ra
f e
tra $(":button"); ns
n -
$(":input"); a no
h a s eฺ
ฺ r s ) u id
ms dent G
$(":submit");
e
@ Stu
a n
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
s $('h1').html("Replacing headers of the web
For example,
k
V u
page").css("color","blue"); replaces the HTML content of each h1 element and sets
l a n
Mi the font color to blue.
Custom jQuery Selectors
Some selectors are available in jQuery and they are not part of the CSS specification. Some
of these custom jQuery selectors are:
• $(":has(selector)"): Selects all elements that match the selector that is sent as a
parameter
• $(":contains(text)"): Selects all elements that contain the specified
p text
• $(":eq(index)"): Selects the element at index n. The index starts at 0.
• $(":not(selector)"): Selects all elements that do not match the selector that is
sent as a parameter
• $(":file"): Selects all elements with the type “file”
• $(":button"): Selects all elements with the type “button”
• $( :input ): Selects all input elements
$(":input"):
• $(":submit"): Selects all elements with the type “submit”
• $(":visible"): Selects all visible elements in the document

JavaScript and HTML5: Develop Web Applications 10 - 8


Inserting DOM Elements

$("p").append("<strong>More text here</strong>");


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("<strong>More text here</strong>").appendTo("p");

$("header h2").insertAfter("#section-3 header h1");

$("#section-3 header h1").after($("header h2"));

$("header").html();
n s e
ice
$("p").html("<strong>Replacing text here</strong>"); b l el
fe r a
a n s
-tr
$("header").text();
o n
$("p").text("Replacing text here"); a n
h a s eฺ
$("h1").wrap("<div></div>");sฺrs
) u id
e m dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ksinsert content on the fly. For example, you can create and insert new elements as
You can
u
V in the code in the slide:
shown
l a n
Mi • .append(content):
pp ( ) Inserts content at the end of the matched elements. To insert at
the beginning, use .prepend(content).
• .appendTo(selector): Serves the same purpose as .append(), except that the
syntax is different, as shown in the code in the slide
• .insertAfter(target): Inserts elements after the target specified. To insert before
the target, use .insertBefore(target).
• .after(content): Inserts content after the matched elements. To insert content
before, use .before(content). This function accepts only content as parameters. If
you want to specify an element, you should surround it with $(), as in the example.
• .html(): Queries and sets the HTML content of an element. html() with no
arguments returns the HTML content of the first matched element. With an argument,
the string passed replaces the existing content.
• .text(): Queries and sets the plain-text of an element
• ( l t ) Wraps
.wrap(selector): W an HTML element
l t around
d each
h matched
t h d element.
l t Th
The
example in the slide wraps a div element around each h1 element.

JavaScript and HTML5: Develop Web Applications 10 - 9


Replacing or Removing DOM Elements

• Replace:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("<strong>Replacing h1
Elements</strong>").replaceAll("h1");

$("h1")
$( h1 ).replaceWith(
replaceWith("<strong>Replacing
<strong>Replacing h1
Elements</strong>");

n s e
• Remove: ice
b l el
f er a
$("#section-1").empty();//
$ p y ;// results in s
tran
<section id="section-1"></section>
n -
n o
$("#section-1").remove();// removes s aeverything,
) h a deฺ
ฺrs t Gui
including <section id="section-1"></section>
s
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
ks or remove content on the fly, some of the available functions are as follows:
To replace
u
an •V .replaceAll(target): Replaces each target element with the matched elements
Mil • replaceWith(): Serves the same purpose as .replaceAll(),
.replaceWith(): replaceAll() except that the
syntax is different, as shown in the code in the slide
• .empty(): Removes all children, including text nodes, of each of the selected elements
• .remove(): Removes all elements in the jQuery object, including the element itself
• .detach(): Is the same as .remove(), except that it returns the detached element for
further manipulation

JavaScript and HTML5: Develop Web Applications 10 - 10


Setting Tag Attributes

• Classes:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("aside p").addClass("sponsors");
$("aside p").hasClass("advertising");
$("aside p").removeClass();

• CSS:

$("h1").css("font-weight"); //For the first h1 element


n s e
ice
el
$("h1").css("background-color", "cyan");
a b l
fe r
• Attributes:
Att ib t a n s
o n -tr
$("input").attr("required"); //For the n first input found
$("input#email").attr("required", a
a
s eฺ
"required");
s ) h id
$("input#email").removeAttr("required");
ฺ r u
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
ks a
• .addClass(className): Adds the specified class or classes to the matched
u
an V elements
Mil • .hasClass(className):
(
one of the matched elements
) Returns true if the specified
p class is assigned
g to at least

• .removeClass(className): Removes a class or classes, or all classes from the


matched elements. If no class is specified as a parameter, all classes are removed.
• .css(): Gets or sets the CSS styles of an element. It returns numeric values as strings.
When writing the CSS properties, it accepts camel case too (for example, fontWeight
in the slide).
• .attr(): Gets or sets HTML attributes of the matched elements. You can set several
attributes simultaneously.
• .removeAttr(attributeName): Removes an attribute from the matched elements

JavaScript and HTML5: Develop Web Applications 10 - 11


Traversing DOM Elements

Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("nav").children().css({"color":"red","border":"2px
dotted red"});
$("#section-1 header").siblings().css("background-
color" "cyan");
color",
$("li:first").nextAll().css("background-color", "red");

$("li:first").next().css("background-color", "red");
n s e
ice
$("li:last").prev().css("background-color", "red"); b l el
f er a
an s
$("header h2").parent().css("background-color","cyan");
- t r
n on
$("#section-1").add('#section-2').css("background", s a
"yellow"); ) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
ks a
• .children(): Returns the children of the element
u
an •V .siblings(): Returns the siblings of the element
Mil • nextAll(): Returns following siblings of the element
.nextAll():
• .next(): Returns the next sibling of the element
• .prev(): Returns the previous sibling of the element
• .parent(): Returns the parent of the element
• .is(selector): Checks the matched element against a selector and returns true if at
least one element matches the selector. It is normally used inside an event handler to
check a condition of the element listened
listened.
• .add(): Adds an element to the set of matched elements. It creates a new set; it does
not alter the original set.

JavaScript and HTML5: Develop Web Applications 10 - 12


Traversing DOM Elements

Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("#section-1").find("p");

$("li").eq(2).css({"color":"red","border":"2px dotted
red"});
});

$("li").first().css("background-color", "red");

n s e
$("li").last().css("background-color", "red");
ice
b l el
fe r a
$("li a").map(function() { a n s
return this.textContent; Returns the n tr
-names of
o
})
s a n in the
the sections
h a deฺ
navigation
ui menu
.get()
rs )
.join();
m sฺ nt G
@ e ude
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
s a
• .find(selector):
k Is similar to the children() method. It returns the descendants
u
V of the matched elements, except that the find() method searches through all levels
an
Mil (child, grandchild, great-grandchild, and so on) instead of only the direct descendants,
as the children() method does. For instance, $('#section-
1').children('p') returns an empty list because the paragraph elements are two
levels below #section-1, whereas $('#section-1').find('p') finds and
returns the list of paragraph elements.
• .eq(index): Returns the element at the index position of the set of matched
elements. The supplied index is zero-based. If a negative index is provided, the starting
point is at the end of the set of the matched elements.
• .first(): Returns the first element in the set of matched elements
• .last(): Returns the last element in the set of matched elements
• .map(callback): Applies a callback function to each element of the matched
elements. It returns a jQuery object with the return values.

JavaScript and HTML5: Develop Web Applications 10 - 13


DOM Element Methods

• Examples:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("section").get(0); // Returns the first section


// or
$("section")[0]; // Using the dereferencing operator

$("section").get(); //Returns an array with all sections


// or
$("section").toArray(); // All sections as an array
n s e
ice
• Examples: b l el
fe r a
a n s
$("section").size(); //Returns 3, the number
o n -trof sections
// or n
$("section").length; // preferred s a ฺ
) h a de
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
s a
• .get(index):
k Returns the element at the index specified. The supplied index is zero-
u
V based. Alternatively, you can use the array de-referencing operator,[index], as shown
an
Mil •
in the code in the slide.
.get(): Returns all the elements matched
• .toArray(): Returns all the elements that are matched as an array
• .size(): Returns the number of elements
• .length: Is the property that specifies the number of elements. Use of length is
preferred because it does not involve a function call like size().
Traversing Collections
Call each(function) to loop over all the elements in a jQuery object and if you require to
handle each element of the object in a different way. Often, it is not necessary to call this
function because jQuery automatically iterates over all elements when calling a method.
For more information about the methods seen in this section, visit http://api.jquery.com/.

JavaScript and HTML5: Develop Web Applications 10 - 14


Example: jQuery Selectors

Use the JSConsole web application and run the following


example (click the play symbol) to practice the examples provided
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

in this section.

Ti
Time Li
Limit:
it 15 minutes
i t

n s e
ice
b l el
Try er
y this ssection
f a
- t r an
in JSConsole.
no n
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
To write and test the jQuery code for the examples in this lesson in JSConsole, click Run (the
u
V
play symbol) in the jQuery example for this lesson. After the main page opens, press F12 (or
an
Mil select Firefox > Web Developer > Firebug > Open Firebug) to open Firebug. In Firebug’s
console, you can try the examples provided in this section.
The code in JSConsole is the same as in the slides. You can refer to the slides at any time
while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 10 - 15


Topics

• jQuery Basics
• Selectors and DOM
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Events
• Animation and Effects
• Ajax
• jQuery UI
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 16


Handling Events in jQuery

• bind() function:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("#myText").bind("click", function() {
$("#myText").addClass("increased-size");
});

• delegate() function: Extra parameter


n s e
$("#myParagraphs").delegate("p", "mouseover", function() lice
a b le
er
{
$(this) addClass("increased-size");
$(this).addClass( increased size );
n s f
}); -tra on
a n
h a s eฺ
) i d
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks it is possible to set up event handling in the web application. The type of events
With jQuery,
in V u
jQuery is categorized in the Browser, Document Loading, Form, Keyboard, and Mouse
l a n
Mi events. For these events, there are some predefined functions, for instance:
• In the category of mouse events: mouseenter(), mousemove(), mouseout(),
mouseover(), mouseup(), hover(), click(), and so on
• In the category of keyboard events: keydown(), keypress(), and so on
You can also use on(), bind(), and delegate() to bind event handlers to events, for
predefined and non-predefined events.
You can bind more than one event handler to the same event by y using
g .bind(). It accepts
p
three arguments: event type, data, and the function handler. In the code example in the slide,
the text identified with #myText increases its size when a user clicks it. By using unbind(),
you remove any bindings for your event: $("#myText").unbind("click");.
Try this and all examples for this section in JSConsole by clicking the Pencil icon for the
“jQuery Events” examples.
With delegate(), you can bind a handler independently of whether the DOM element exists
or not.
t Th
The code
d example l iin th
the slide
lid attaches
tt h a mouseover eventt handler
h dl tto every new
paragraph created by clicking the “Add a paragraph” button. With undelegate(), you
remove the binding: $("#myParagraphs").undelegate("p", "mouseover");.

JavaScript and HTML5: Develop Web Applications 10 - 17


Handling Events in jQuery

• on() function:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("#myText").on("click", function() {
$("#myText").addClass("change-color");
}); Extra parameter

$("#myParagraphs").on("mouseover", "p", function()


{
$(this).addClass("change-color"); n s e
ice
});
b l el
fe r a
• Triggering
Ti i an E
Event:
t a n s
o n -tr
$( "#myText" ).trigger( "click" );
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
Starting
k a
swith version 1.7, jQuery has the on() method that supersedes bind(),
V u
delegate(), and live() (the last one is not recommended). It accepts an event type and a
l a n
Mi handler function to execute. The code in the slide adds an event handler to the HTML
snippets previously shown but this time by using the on() method.
With the off() method, you remove the binding: $("#myText").off("click"); or
$("#myParagraphs").off("mouseover", "p");.
Triggering Events
You can programmatically execute event handlers without the need for the event to occur with
trigger(), which executes event handlers for an event type.
By adding event.stopPropagation() in an event handler, you can prevent the event
from bubbling to outer elements. This prevents any parent event handlers from being
executed. And with event.preventDefault(), a handler can cancel any default action
that the browser may have for this event, for example, preventing a submit button from
submitting a form.
The event handlers can receive an event parameter, which is an event object. When using
t i
trigger(),() you can build this object by calling the jQuery.Event()
jQ E t() constructor.
constructor
For more information about events, visit http://api.jquery.com/category/events/.

JavaScript and HTML5: Develop Web Applications 10 - 18


Example: jQuery Events

Use the JSConsole web application and run the following


example to see the examples provided in this section in action.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 5 minutes

n s e
ice
b l el
Tryy thissfer a
section
- t r anin
n on
s eฺ a JSConsole.
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Interactk a
s the elements on the web page on the Preview tab and read the code in
with
u
V to understand how events are handled. Uncomment the lines in the code.js file to
code.js
l a n
Mi try the on() method as well.
The code in JSConsole is the same as in the slides. You can refer to the slides at any time
while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 10 - 19


Topics

• jQuery Basics
• Selectors and DOM
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Events
• Animation and Effects
• Ajax
• jQuery UI
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 20


Applying Effects

• show() and hide():


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$(document).ready(function() {
$("#myText").hide();
$("#myButton").on("click", function() {
$("#myText").show();
y
});
});

n s e
• toggle(): ice
b l el
$("#myToggleButton").on("click", function() {
f er a
$("#myText").toggle(); an s
}); n - t r
a no
h a s eฺ
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
jQuery provides a set of methods for animating elements in the document.
u
V
• show(): Displays the matched elements. It accepts the duration of the effect as a
an
Mil parameter,
pa a ete , in milliseconds.
seco ds In suc
such a case, tthe
eeelement
e e t will be fully
u y visible
sbeu
of the duration is over. 'slow' and 'fast' can be used to indicate 600 and 200
until
t tthe
e ttime
e

milliseconds, respectively. If the duration parameter is not specified, the default (400 ms)
is used.
• hide(): Hides the matched elements. The duration parameter can also be used here
and also in the next method.
• toggle(): Displays or hides the matched elements, toggling their visibility
The Callback Function
The methods described in the preceding paragraph accept as a parameter a function to call
after the animation is complete, for example:
$("#myButton").on("click", function() { $("#myText").show(function()
{
console.log("Animation complete");
}); });

JavaScript and HTML5: Develop Web Applications 10 - 21


Applying Effects

• slideDown() and slideUp():


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("#mySlideButton").on("click", function() {
$("#myText").slideDown();
});
$("#mySlideHideButton").on("click",
$( #mySlideHideButton ).on( click , function() {
$("#myText").slideUp();
});

n s e
• fadeIn() and fadeOut(): ice
b l el
$("#myFadeButton").on("click", function() {
f er a
$("#myText") fadeIn();
$("#myText").fadeIn();
an s
- t r
on {
});
n
$("#myFadeHideButton").on("click", function()
a
$("#myText").fadeOut();
h a s eฺ
}); rs ) u i d
m sฺ nt G
@ e ude
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
• slideDown(): Displays the elements with a sliding effect
u
•V slideUp(): Hides the elements with a sliding effect
an •
Mil fadein(): Displays the elements with a fade effect; makes the elements opaque
• fadeOut(): Hides the elements with a fade effect; makes the elements transparent
The duration parameter and the callback function can also be used as parameters in these
functions.
Chaining Effects
jQuery allows the chaining of different methods, which enables a user to apply multiple effects
in sequential
seq ential order
order. The e
example
ample in JSConsole chains methods in the follo
following
ing order
order:
$("#myText").slideDown().slideUp().fadeIn().fadeOut();

JavaScript and HTML5: Develop Web Applications 10 - 22


Custom Effects

animate():
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("").animate({property: value, property: value},


[duration,] [easing,] [callback]);

$("#myAnimateButton").on("click", function() {
$("#myImg").animate({
height: 400, n s e
width: 400, lice
opacity: "hide"}, a b le
2000); s f er
n
}); -tra on
a n
h a s eฺ
) i d
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
ks a
The animate() function enables you to create your own custom animations. As shown in
u
theVslide, this function receives as parameters:
l a n
Mi 1. An object ofo sty style
e properties
p ope t es a
and
d values,
a ues, which
c aare
e tthe
epproperties
ope t es to a
animate
ate
2. The duration (optional)
3. The easing argument (optional), which determines how fast the animation runs at
different points of time
4. The callback function, to execute after the animation is complete
The animate() function enables you to change more than one attribute at a time. This is
shown in the second code snippet in the slide.
Properties can have the shortcut "hide", which will animate the property from its current
value toward 0, or "show", which will animate the property toward its current and saved
value. Properties can also be relative if a value is specified with += or -=. Try, for example,
replacing the value "hide" with "-=.75" for the property opacity. Then, the opacity of the
image is computed by subtracting .75 from the current value.

JavaScript and HTML5: Develop Web Applications 10 - 23


Custom Effects

Queuing:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("#myQueueAnimateButton").on("click", function() {
$("#myImg").animate({height: 400}, 1000)
.animate({width: 400}, 1000)
.animate({opacity: "-=.75"},
.75 }, 1000); });

$("#myManualQueueAnimateButton").on("click", function()
n s e
{
lice
$("#myImg").queue(function() {
a b le
$(this).animate({height: 400}, 1000);
s f er
$(this) dequeue()
$(this).dequeue();
- t r an
});
n on
}); a s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
a
ks snippet in the slide shows a chained animation, where each animation starts after
The code
u
theVprevious animation is completed.
l a n
Mi A similar effect of queued animations is reached by using the queued() and dequeued() functions, as shown in the second code snippet in the slide. Notice that dequeue() must be
called immediately in order to run the animation.

JavaScript and HTML5: Develop Web Applications 10 - 24


Custom Effects

$("#myNonQueueAnimateButton").on("click", function() {
$("#myImg")
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

.animate({
height: 400
options object
}, {
duration: 1000,
queue: false,
easing: "linear"
})
n s e
.animate({width: 400}, 1000)
lice
.animate({opacity: "-=.75"}, 1000);
a b le
}); er f
t r a ns
no { n-
a
$("#myStopButton").on("click", function()
s eฺ
$("#myImg").stop();
h a
}); ฺrs) uid
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
The second
k a
s form of animate() is by using an options object that allows you to set options
forV u
queuing and easing. The code snippet in the slide shows how for the height property the
l a n
Mi animation is unqueued by setting queue: false, in addition to setting a duration and easing.
This means that height will animate at the same time as width. After width is complete, the
opacity animation will begin.
Stopping Animations
finish() and stop() stop any currently executing animations on the matched elements
and make them jump to their end values. Except that finish() causes all queued
animations to jump to their end values as well. The code snippet in the slide shows the
t () function.
stop() function You can try to stop and finish functions in JSConsole while running an
animation.
Disabling jQuery Animations
You can disable animations by assigning true to the global jQuery object jQuery.fx.off.

JavaScript and HTML5: Develop Web Applications 10 - 25


Example: jQuery Effects

Use the JSConsole web application and run the following


example to see the examples provided in this section in action.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 10 minutes

n s e
ice
b l el
Try this er a
section
ti n sin
i
f
-tr a
n o n
JSConsole.
s a
) h a
i d eฺ
s ฺrs t Gu
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Click the buttons on the web page on the Preview tab to see the different animations and
u
V
effects in action. Try also, for example, to provide different duration values to methods by
an
Mil modifying the code in the code.js file.
When experimenting with the animations, do not forget to click the Reset image button after
each try to see each animation effectively.
The code in JSConsole is the same as in the slides. You can refer to the slides at any time
while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 10 - 26


Topics

• jQuery Basics
• Selectors and DOM
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Events
• Animation and Effects
• AJAX
• jQuery UI
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 27


AJAX

• Syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$.ajax(<url> [,settings]);
// or
$.ajax({ url: "myUrl" [, settings] });

• Example:
$("#ajaxButton").on("click", function() {
n s e
var request = $.ajax({
lice
url: "data/file_1.html",
a b le
type: "GET",
s f er
dataType: "html"
- t r an
on
});
request.done(function(data) {
a n
$("#content").html(data);
h a s eฺ
) i d
});
s ฺrs t Gu
}); m n
e ude
a n @ S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
You learned about AJAX and how to use it with JavaScript in the lesson titled “AJAX and
u
V
WebSocket.” In this section, you learn about the jQuery AJAX methods to make server calls.
an
Mil jQuery provides the ajax() method but also provides wrapper methods to implement AJAX
requests.
The ajax() method enables you to make AJAX requests but with more flexibility and control.
In the slide, the syntax shows how to perform an asynchronous HTTP (HTTP) request. The
second code snippet shows an example of using this method.
The example in the slide sets, in addition to the URL, other key/value pairs, such as the type
of data expected back from the server, The web server returns different data types: static
HTML ttext,
HTML, t XML
XML, a JSON fil
file, and
d so on. The
Th examplel also
l setst th
the ttype off requestt to
t “GET”
although it is already the default.
The ajax() method returns an XMLHttpRequest (jqXHR) object, which contains several
methods (in the example, the done() method is used, which is called when requests
complete successfully) to add the HTML data returned by the server (local file, in your
example) to a div element.
To know more about the configuration parameters allowed in ajax(), visit
http://api.jquery.com/jQuery.ajax/.

JavaScript and HTML5: Develop Web Applications 10 - 28


Handling Server Response

• load():
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("#loadButton").on("click", function() {
$("#content").load("data/file_1.html");
});

• getScript():
n s e
$("#scriptButton").on("click", function() { lice
$.getScript("scripts/myscript.js", function() { abl
e
console.log("Here
console.log( Here some actions after the script s f er is
loaded"); - t r an
}); n on
a
}); as )
ฺh de
r s u i
m sฺ nt G
@ e ude
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Often, it is not necessary to call the ajax() method, because there are shorthand AJAX
u
V
functions that are easier to use. These are explained next.
an
Mil One of these shorthand functions is load(), which loads data from the server and places the
returned HTML into the matched element (div element, in the example). XML and HTML
data are returned as a DOM object. This method also accepts callback functions to execute
when the request completes.
With getScript(), you can load a JavaScript file and execute it. In the example in the slide,
myscript.js is loaded and executed. myscript.js calls the load() function.

JavaScript and HTML5: Develop Web Applications 10 - 29


Handling Server Response

Handling JSON data:


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("#jsonButton").on("click", function() {
$.getJSON("data/list.json", function(data) {
$.each(data, function (key, val) {
$("#content ul").append("<li
ul") append("<li id='" + key + "'>"
+ val + "</li>");
});
});
n s e
ice
el
});
a b l
fe r
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
To loadk a
sJSON-encoded data from the server, you can use the getJSON() function, which
u
V url, data, and callback as parameters.
naccepts
a The example in the slide loads a JSON file that contains: {
Mil "1":
1 : "Peter",
Peter , "2":
"Mike", "3": "Tom", "4": "Matt", "5": "Cindy" }. When the server sends a
2 :

JSON response, the JSON data is automatically converted to a JavaScript object. In the
example, this object is traversed to append each key and value to an unordered list in the
page.

JavaScript and HTML5: Develop Web Applications 10 - 30


Handling Server Response

• get() syntax:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$.get(<url> [,data][,success][,dataType]);

• get() example:

$("#getButton").on("click", function() {
n s e
$.get("data/file_1.html", function(data) { lice
$("#content").html(data);
a b le
}, "html");
} s f er
}); tran n -
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
Generic s a
kGET/POST Requests
u
ForVgeneric requests, you can use get() and post() methods.
l a n
Mi get(): Sends and receives data by using an HTTP GET request. It accepts as parameters:
• url: The URL of the file to get
• data: An object that can be sent to the server
• success: The callback function to execute on success
• dataType: The type of data expected from the server. The type parameter that these methods
accept as a string are “xml,” “html,” “script,” “json,” “jsonp,” or “text.”
post(): Sends and receives data as well, but using an HTTP POST request. The syntax of this method
is the same as get().
The example in the slide shows how to load data from an HTML file, and set loaded content into the
div element with id=content.
.get() enables you to chain multiple callbacks. These callbacks are done(), fail(), and
always(), which are called when a successful message, failed message, or a response from the
server, respectively, are received.

JavaScript and HTML5: Develop Web Applications 10 - 31


Example: jQuery Ajax

Use the JSConsole web application and run the following


example to see the examples provided in this section in action.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Time Limit: 10 minutes

n s e
lice
Try this ble
section f e
in
ra
t r a ns
-
onJSConsole.
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
a n(
ks
Click the buttons on the web page on the Preview tab to see the different AJAX calls.
u
V
i l anWhen experimenting with the examples, do not forget to click the Clear content button after
M each try to see each AJAX call effectively.
Note: To see the getJSON() request content, you might need to refresh your browser first.
The code in JSConsole is the same as in the slides. You can refer to the slides at any time
while reviewing the code in JSConsole.

JavaScript and HTML5: Develop Web Applications 10 - 32


Topics

• jQuery Basics
• Selectors and DOM
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Events
• Animation and Effects
• Ajax
• jQuery UI
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 33


Adding jQuery UI to Your Project

<!DOCTYPE html>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<html>
<head>
<title>The Next Big Front-End Conference</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="scripts/jquery-ui-
1.11.1.custom/jquery-ui.css" />
<script src="scripts/jquery-1.11.1.js"></script>
n s e
<script src="scripts/jquery-ui-
lice
1.11.1.custom/jquery-ui.js"></script>
a b le
</head>
s f er
<body>...</body>
b d /b d
- t r an
no
</html> n
a
s eฺ
Choosing theme at h a
Download Builder ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

m i lan to us
n (
a
s a built-in method for extending its functionality via plug-ins, thus allowing other
jQuerykhas
V u
programmers to create plug-ins. The jQuery UI library is a collection of plug-ins related to
l a n
Mi managing the user interface.
To use the jQuery UI, you need to link the file to your web page by using the <script>
element on the HTML page, as shown in the slide.
You can download and use a customized local copy that you can get from the jQuery UI site
at http://jqueryui.com/download/ or through Content Delivery Networks (CDN). On the
Download Builder page at http://jqueryui.com/download/, you can choose the version,
components, and the theme. In this section, you use version 1.11.1, all the components, and
th d
the default
f lt th
theme.
jQuery CSS Themes
Different CSS files make a theme, and each theme provides a different look-and-feel for the
different screen elements. The screenshot in the slide shows the selection of theme on the
Download Builder page. The code snippet in the slide uses the base theme; if you prefer a
different style, you can append the word .theme to the word jquery-ui, in which case the
file name to refer would be jquery ui.theme.css, which contains the theme that you
jquery-ui.theme.css,
selected on the Download Builder page.

JavaScript and HTML5: Develop Web Applications 10 - 34


jQuery UI Components
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n ( mil to u
k
After you a
sdownload and decompress the selected Query UI zip file, it is recommended that
u
Vopen and read the index.html page within the decompressed folder, which shows
you
l a n
Mi some of the features of the jQuery UI in a browser. You can open this file by using
JSConsole.
Widgets
In the examples for this lesson in JSConsole, there is the link to “jQuery UI Features
Reference.” Click the play symbol to go to the URL. The index.html page is shown, where
you can play with the different widgets provided by the jQuery UI. The theme shown for the
widgets is the theme that was previously selected. The screenshot in the slide shows the
i d ht l page.
index.html page
Interactions and Effects
Besides widgets, the jQuery UI adds interactions, such as drag-and-drop, selection, and
resizing. It also adds a comprehensive set of effects, in addition to the built-in effects in
jQuery.
Details about how to implement widgets, interactions, and effects can be found at
http //jq er i com/ However,
http://jqueryui.com/. Ho e er you o can usese JSConsole as the sandbox
sandbo and tr
try to add the code
found in the jQuery UI official reference to the index.html and code.js pages in the
“jQuery UI” example for this lesson:

JavaScript and HTML5: Develop Web Applications 10 - 35


Where Can I Learn More?

Resource Website
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

jQuery API http://api.jquery.com/

jQuery UI http://jqueryui.com/

jQuery UI API http://api.jqueryui.com/


n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 36


Summary

In this lesson, you should have learned how to:


• Add jQuery and jQuery UI libraries to your projects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

• Use selectors and DOM manipulators to handle documents


• Handle events with jQuery
• Animate elements and apply effects in the document
• Handle AJAX server responses
n s e
ice
b l el
fe r a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
uksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 37


Course Road Map

Day I Day II Day III Day IV


Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Document Style Dynamic Data


Introduction Object Model Applications with AJAX and
with CSS3 WebSocket

Web The Advanced Developing


Application JavaScript API JavaScript Applications with
Essentials JQuery

n s e
ice
el
JavaScript Application
Fundamentals Data

a b l
fe r
a n s
n - tr
o
Day
s an
) h a deฺ
ฺrs t Gui
Hands-On Practice
s
Lecture

@ em uden
a n S t
s
uk e thi s
ฺ v Copyright © 2014 Oracle and/or its affiliates. All rights reserved. |

an s
n (mil to u
u ksa
n V
a
Mil

JavaScript and HTML5: Develop Web Applications 10 - 38

You might also like