0% found this document useful (0 votes)
36 views

JS&HTML5 - Develop web application_ag

The document is an activity guide for developing web applications using JavaScript and HTML5, published by Oracle. It includes a disclaimer about copyright and proprietary information, as well as a table of contents outlining various lessons and practices related to web application development. The guide is intended for use in Oracle training courses and covers topics such as creating HTML5 applications, JavaScript fundamentals, and AJAX.

Uploaded by

Boban Vasiljevic
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

JS&HTML5 - Develop web application_ag

The document is an activity guide for developing web applications using JavaScript and HTML5, published by Oracle. It includes a disclaimer about copyright and proprietary information, as well as a table of contents outlining various lessons and practices related to web application development. The guide is intended for use in Oracle training courses and covers topics such as creating HTML5 applications, JavaScript fundamentals, and AJAX.

Uploaded by

Boban Vasiljevic
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 166

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
Activity Guide
D84842GC10
Edition 1.0 | Dec 2014 | D88939

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


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

Disclaimer

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 constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization
of Oracle.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

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 Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.

Restricted Rights Notice

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:

U.S. GOVERNMENT RIGHTS


The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or disclose these training materials are restricted
n s e
by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.
ice
Trademark Notice
b l el
fe r a
owners.
a n s
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective

o n -tr
Authors
s an
Eduardo Moranchel, Edgar Martinez
) h a deฺ
s ฺ rs t Gui
Technical Contributors and Reviewers m n
@
Michael Williams, Girija C, Eric Jendrock,
eSebastien
u d eColas, Veerabhadra Rao Putrevu, Iris Li,
a n S t
uks e this
Glenn Stokol
ฺ v
i lan tousing:
This book was published
m us Oracle Tutor
n (
ks a
u
anV
Mil
Table of Contents
Practices for Lesson 1: Introduction ..............................................................................................................1-1
Practices for Lesson 1: Introduction ...............................................................................................................1-2
Practices for Lesson 2: Web Application Essentials ....................................................................................2-1
Practices for Lesson 2: Overview ...................................................................................................................2-2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Practice 2-1: Creating HTML 5 Web Applications with NetBeans 8 ...............................................................2-3


Practice 2-2: Separating JS and CSS Resources ..........................................................................................2-7
Practice 2-3: Creating a Navigational HTML 5 Application .............................................................................2-11
Practices for Lesson 3: JavaScript Fundamentals .......................................................................................3-1
Practices for Lesson 3: Overview ...................................................................................................................3-2
Practice 3-1: Passing JavaScript Tests in JSConsole with Jasmine ..............................................................3-3
Practices for Lesson 4: Combining HTML5 and JavaScript in Web Applications......................................4-1
Practices for Lesson 4: Overview ...................................................................................................................4-2 n s e
ice
el
Practice 4-1: Writing JavaScript Code to Modify Document Elements ...........................................................4-3
b l
f e ra
Practices for Lesson 5: The JavaScript API ..................................................................................................5-1

ns
Practices for Lesson 5: Overview ...................................................................................................................5-2

r a
Practice 5-1: Bill Calculator by Age ................................................................................................................5-3
- t
n
Practice 5-2 (Optional): Changing Inputs for Birth Dates ...............................................................................5-12
o
an
Solution 5-2: Changing Inputs for Birth Dates ................................................................................................5-13
s
h a deฺ
Practices for Lesson 6: Web Application Data ..............................................................................................6-1
)
ฺ rs t Gui
Practices for Lesson 6: Overview ...................................................................................................................6-2
s
Practice 6-1: Creating a To-Do Application with Local
e mStorage d e n .............................................................6-7
......................................................................6-3
Practice 6-2 (Optional): Adding a Remove Completed
a @ t u
Tasks Button
n.....................................................................................................6-8
S
Solution 6-2: Removing Completed Tasks
s
uk e Using s
hi CSS3 and JavaScript ....................................................7-1
Practices for Lesson 7: Style v
ฺ Applications t
n ...................................................................................................................7-2
i
Practices for Lesson 7: laOverview u s
m o
( Elementstwith CSS3......................................................................................................7-3
Practice 7-1: Styling
a n
Practicessfor Lesson 8: Advanced JavaScript...............................................................................................8-1
V uk for Lesson 8: Overview...................................................................................................................8-2
Practices
an
Mil
Practice 8-1: Painting in an HTML5 Canvas Element ....................................................................................8-3
Practice 8-2: Creating an Interval to Paint in a Canvas Element ....................................................................8-6
Practice 8-3: Implementing Drag and Drop to Paint Images on the Canvas ..................................................8-9
Practice 8-4: Painting the Canvas with Mouse Gestures ...............................................................................8-12
Practices for Lesson 9: AJAX and WebSocket..............................................................................................9-1
Practices for Lesson 9: Overview ...................................................................................................................9-2
Practice 9-1: AJAX and REST .......................................................................................................................9-3
Practice 9-2: WebSocket ................................................................................................................................9-11
WebSocket Messages ...................................................................................................................................9-13
Appendix JSConsole Examples......................................................................................................................10-1
Lesson 3 JavaScript Fundamentals ...............................................................................................................10-2
Lesson 4 Combining HTML5 and JavaScript in Web Applications .................................................................10-11
Lesson 5 The JavaScript API .........................................................................................................................10-23
Lesson 6 Application Data .............................................................................................................................10-30
Lesson 7 Style Applications Using CSS3 and JavaScript ..............................................................................10-33
Lesson 8 Advanced JavaScript ......................................................................................................................10-38
Lesson 9 AJAX and WebSocket ....................................................................................................................10-53
Lesson 10 Developing Applications with jQuery ............................................................................................10-62
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

JavaScript and HTML5: Develop Web Applications Table of Contents


iii
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

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

JavaScript and HTML5: Develop Web Applications Table of Contents


iv
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
o n -tr
Practices aforn Lesson 1:
s
a deฺ
Introduction
h
)
ฺrs 1t Gui
s
Chapter
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n ( mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 1
Practices for Lesson 1: Introduction
Practices Overview
There are no practices for this lesson.
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

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 2
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
o n -tr
Practices afor n Lesson 2: Web
s eฺ
a dEssentials
Application
h
)
ฺrs 2t Gu i
s
Chapter
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 1
Practices for Lesson 2: Overview
Practice Overview
In these practices, you create, run, and debug an HTML 5 application.
You can complete these practices in your own environment by using NetBeans 8.
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

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 2
Practice 2-1: Creating HTML 5 Web Applications with NetBeans 8
Overview
In this practice, you create a new HTML5 application by using NetBeans 8 with a single HTML
file with JavaScript code and CSS styles.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Tasks
1. Open NetBeans and select File > New Project.

n s e
i ce
b l el
2. Select the HTML5 category and the HTML5 Application project. Click Next.
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

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 3
3. Enter lab_02_01 as the project name and browse to
/home/oracle/labs/activities/ for Project Location. Click Finish.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

An empty project is created with no templates, libraries, or external resources.


4. By default, the index.html file is displayed in the editor. If this is not the case, open it by
double-clicking it on the Projects tab.

n s e
i ce
b l el
fer a
a n s
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s s
i Projects tab and select Run File from the menu.
uk filee onththe
5. v
Right-click the index.html

m i lan to us
n (
a
V uks
an
Mil

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 4
6. A new web browser window opens, displaying the contents of the index.html file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
7. Identify the elements of the URL displayed in the browser’s address bar, and answer the
i ce
following questions:
b l el
What is the server host?
fer a
What port number was used?
a n s
What is the path to the resource?
o n -tr
What HTTP method was used in the request?
s an
) h a deฺ
8. Go back to NetBeans and replace <div>TODO
s ฺrswrite G ui
content</div> in the
index.html file with the following HTMLem code: en t
n @ t u d
<h1>Hello</h1>
s a s S
v uk e thi
<p>Hi <span id="nameSpan">you</span>!.</p>

9.
m lan to usfile and select Run File from the menu.
Right-click the iindex.html
Notice n
how ( the content displayed in the web browser changed to reflect the changes in the
ks a file.
V uindex.html
10. Go back to NetBeans and add the following CSS Style tag and code above the </head>
an
Mil tag.
<style>
body{
font-family: Arial;
background-color: #d9e7f2;
margin: 0px; border: 0px; padding: 0px;
}
h1{color: #18466a;}
#nameSpan{font-weight: bold;}
</style>
11. Run the application again and notice the style changes.

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 5
12. Add the following JavaScript code above the </body> tag in the index.html file:
<script>
var nameSpan = document.getElementById("nameSpan");
nameSpan.innerHTML = "John";
</script>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

13. Replace “John” with your name and run the application. Notice how the name is changed.

n s e
i ce
b l el
fer a
a n s
o n -tr
s aandnJavaScript by using
Congratulations! You created an HTML5 application with a
NetBeans. ) h CSS
i d eฺ
s
You can find the solution files for this practice in
rs t Gu
ฺthe
/home/oracle/labs/solutions/lab_02_01/
@ em udefolder. n Use solution files for reference and if
you need to copy any code. a n S t
s
uk e thi s
ฺ v
m i lan to us
n (
ks a
u
anV
Mil

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 6
Practice 2-2: Separating JS and CSS Resources
Overview
In this practice, you separate CSS styles and JavaScript code into different archives.

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

You have completed practice 2-1.

Tasks
1. In NetBeans, right-click the Site Root node and select New > Folder.

n s e
i ce
b l el
fer a
a n s
n - tr
o
s an
) h a deฺ
2. Name the folder styles and click Finish. ฺrs
s G ui
e m dent
a n @ Stu
ฺ v uks e this
m i lan to us
n (
ks a
V u
an3.
Mil Right-click the newly created styles folder and select New > Cascading Style Sheet.

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 7
4. Enter simple as the file name and click Finish.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

The newly created file opens in the editor. If this is not the case, double-click the file name
on the Projects tab.

n s e
i ce
b l el
fer a
a n s
o n -tr
You can move between opened files by clicking the tabs above
s a n the editor. You can open a
h a to editdit.eฺ
file by double-clicking it on the Projects tab if you want
)
5. Open the index.html file, select the contents
s ฺrsof thet G ui tag, and copy them by
<style>
em uden
selecting Edit > Copy or by pressing Ctrl+C.
@
6. Remove the <style> and </style>
s a n tagStalong with its body.
7. Open the simple.cssufile
v k and paste
t h isthe styles you copied from the index.html file at

n use
the bottom of the file.
a
i l
(m codetofor reference:
Use the following
n
a
uks
body{

n V font-family: Arial;
l a
Mi background-color: #d9e7f2;
margin: 0px; border: 0px; padding: 0px;
}
h1{color: #18466a;}
#nameSpan{font-weight: bold;}
8. Press Ctrl+S or select File > Save to save the file.
9. Open the index.html file and add the following link tag above the </head> tag.
<link rel="stylesheet" href="styles/simple.css" />
This links the simple.css file to the index.html file.

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 8
10. Save the index.html file.
11. Right-click the index.html file and select Run File from the menu.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

A browser window opens and displays the page. Note that the contents are the same but
n s e
the style sheet is loaded from the simple.css file.
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
ksa
12. Create a new folder called scripts:

V u  Right-click the Site Root node and select New > Folder.
an
Mil
 Name the folder scripts and click Finish.
13. Right-click the newly created scripts folder and select New > JavaScript File.

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 9
14. Enter greeting as File Name, scripts as Folder, and click Finish.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

15. Open the index.html file.


16. Select the contents of the <script> tag and copy them.
17. Remove the body of the <script> tag. Do not remove the tag itself; leave it empty.
18. Open the greeting.js file and paste the contents of the <script> tag that you copied
at the end of the file.
n s e
19. Save the greeting.js file. li ce
20. Open the index.html file and add the src="scripts/greeting.js" attribute l e
bto the
e r a
script tag. It should look like the following:
a n sf
<script src="scripts/greeting.js"></script>
o n -tr
This links the greeting.js file, and executes it.
s an
21. Save the index.html file.
) h a deฺ
22. Right-click the index.html file and select Run
s ฺrs tfrom
File
G uthei menu.
23. Open the browser’s development tools m
@
notice the requests made to the server. d enthe page. Open the network monitor and
e and urefresh
a n S t
s
ukcontents
24. Answer the following questions: i s
hchange?
ฺ v e t
lanrequests
− Did the browser’s
i u s
− Howm
( many t o did the browser make to the server to display the application?
s a n
Youu k
V can find the solution files for this practice in the folder. Use solution files for reference and if
n/home/oracle/labs/solutions/lab_02_02/
a
Mil you need to copy any code.

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 10
Practice 2-3: Creating a Navigational HTML 5 Application
Overview
In this practice, you create hyperlinks in HTML and reuse the CSS code to create a uniform
presentation.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Assumptions
You have completed Practice 2-2.

Tasks
1. Right-click the Site Root and select New > HTML File.

n s e
i ce
b l el
fer a
a n s
o n -tr
s
2. Enter about as File Name, leave the Folder field empty, a nclick Finish.
and
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
m i lan to us
n (
a
ksthe following link tag above the </head> tag to add the style sheet to the newly
3. uAdd
V created HTML file. Note that you can copy the tag from the index.html file.
an
Mil <link rel="stylesheet" href="styles/simple.css" />
4. In a new line below the <body> tag, add the following anchor tag to add a hyperlink to the
main page:
<a href="index.html">Go Back</a>
Note that the destination of the hyperlink is defined in the href attribute and the label
displayed for the hyperlink is the body of the <a> tag.
You may add more content to the page and modify it as you feel comfortable.
5. Open the index.html file and add the following above the <script> tag:
<ul>
<li><a href="about.html">About</a></li>
</ul>
6. Use the following for reference:
<!DOCTYPE html>
<html>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 11
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<link rel="stylesheet" href="styles/simple.css" />


</head>
<body>
<h1>Hello</h1>
<p>Hi <span id="nameSpan">you</span>!.</p>
<ul>
<li><a href="about.html">About</a></li>
</ul> n s e
i ce
<script src="scripts/greeting.js"></script>
b l el
</body>
fer a
</html>
a n s
7. -
Right-click the index.html file and select Run File from the menu.
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 8. Click the About link.

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 12
9. Answer the following questions:
− What is displayed in the browser’s address bar?
− Why is the background color of the new page blue?
10. Create a new folder in the Site Root called users.
11. Create a new HTML file called list in the users folder.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

n s e
12. Add the following link tag in a new line above the </head> tag to add the style sheet to the
i ce
HTML file.
b l el
<link rel="stylesheet" href="../styles/simple.css" />
f er a
13. Add the following anchor tag in the <body> to add the link back to the a
s
n page:
main
- t r
<a href="../index.html">Go Back</a>
n on
14. Open the index.html file and add the following tag insa a new line above the </ul> tag.
) h a
i d eฺ
<li><a href="users/list.html">User
s ฺrs t Gu List</a></li>
15. Save all the opened files. m den
eselect
@
16. Right-click the index.html filenand
a S tuRun File.
ฺ v uks e this
m i lan to us
n (
ks a
V u
an
Mil

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 13
17. Navigate by using the links, and in the following screenshot, draw arrows connecting the
links to the pages.
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
m i lan questions:
18. Answer the following
o u s
− n ( a directt link from the user list to the About page?
Is there
a
ks− How do you navigate from the About page to the User list?
V u
an − Why is the style sheet referenced differently in the about and user list page?
Mil
You can find the solution files for this practice in the
/home/oracle/labs/solutions/lab_02_03/ folder. Use solution files for reference and if
you need to copy any code.

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

Practices for Lesson 2: Web Application Essentials


Chapter 2 - Page 14
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
o n -tr
Practices afor n Lesson 3:
JavaScript
h s eฺ
a dFundamentals
)
ฺrs 3t Gu i
s
Chapter
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n ( mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 3: JavaScript Fundamentals


Chapter 3 - Page 1
Practices for Lesson 3: Overview
Practices Overview
In the practices for this lesson, you write JavaScript code to pass some tests with the Jasmine
test framework.
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

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

Practices for Lesson 3: JavaScript Fundamentals


Chapter 3 - Page 2
Practice 3-1: Passing JavaScript Tests in JSConsole with Jasmine
Overview
In this practice, you write JavaScript code in order to get tests to pass.
JSConsole is the web application where tests are located. You can access it by navigating to
http://localhost:8080/JSConsole/ in your browser. In JSConsole, you add the code needed to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

pass the tests described there.


The following graphic shows the main page of JSConsole:

n s e
i ce
The play symbol button runs the practice. If you click this button, you see the Jasmine b l el
results for the current code. Initially, all tests fail.
fer a
The pencil symbol button leads to the practice itself. You can edit the code there to pass a n s
the tests. n - tr
o
an
After opening the practice, you can edit the code in the Edit area to make a test pass. The
s
) h a deฺ
following graphic shows the main components on this screen.

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

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

Practices for Lesson 3: JavaScript Fundamentals


Chapter 3 - Page 3
Every time you modify code in the Edit area, if you think you have passed one of the tests,
click the Run button and see the test results in the Preview Results area. Alternatively,
click the Run in New Window button.
The Revert Changes button replaces the current content with the original content of the
file.
The Solution button opens a window with the code that solves and passes all the tests.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

The Test Results area provides more information about the tests: the purpose of the tests,
and whether the test passed or failed, as shown in the following graphic:

n s e
i ce
b l el
fer a
After some code is added in the Edit area, click the Run button to run the tests against the
a n s
-
current code in the Edit area, as shown in the following graphic:
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
The Preview Test Results area is refreshed, showing the latest test results, as shown in the
following graphic:

Add the necessary code in the Edit area till all tests are passed. After all tests are passed, the
Test Results area becomes green, as shown in the following graphic:

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

Practices for Lesson 3: JavaScript Fundamentals


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

After passing the tests for this section, click the Back button to go to the main page.

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

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

Practices for Lesson 3: JavaScript Fundamentals


Chapter 3 - Page 5
Task
Based on the overview steps detailed in the preceding section, make tests pass for the three
practices listed for the lesson titled “JavaScript Fundamentals” on the main page of JConsole:
1. JavaScript Variables and Types
2. JavaScript Objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

3. JavaScript Functions
As shown in the following graphic:

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

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

Practices for Lesson 3: JavaScript Fundamentals


Chapter 3 - Page 6
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
o n -tr
Practices afor n Lesson 4:
Combiningh s eฺ
a dHTML5 and
) i
ฺrs t Gu in Web
JavaScript
s
@ em Applications
u d en
a n S t
s
uk e thi s Chapter 4
ฺ v
an s
n ( mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 4: Combining HTML5 and JavaScript in Web Applications


Chapter 4 - Page 1
Practices for Lesson 4: Overview
Practices Overview
In the practices for this lesson, you write JavaScript code to manipulate DOM elements as
requested by the practices.
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

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

Practices for Lesson 4: Combining HTML5 and JavaScript in Web Applications


Chapter 4 - Page 2
Practice 4-1: Writing JavaScript Code to Modify Document Elements
Overview
In this practice, you write JavaScript code to modify elements in the document.
The practice for this lesson is located in the web application JSConsole. You can access the
application by navigating to http://localhost:8080/JSConsole/ in your browser. There, you add
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

the necessary code to modify elements in the web document as required.


The following graphic shows the main page of JSConsole:

n s e
i ce
b l el
fer a
a n s
o n -tr
s an
) h a deฺ
s
The pencil symbol button leads to the practiceฺrsitself.tYou
G uediti the code there to modify the
HTML elements.
@ em uden
S t
The play symbol button leadsatonthe index.html file.
After opening the practice,vyou
s s
i code in the Edit area to get the behavior requested
ukcaneeditththe

nlocateduinsthe Preview Results area. The following graphic shows the
for the HTML elements
main components m i
on
lathis to
screen:
n (
u ksa
anV
Mil

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

Practices for Lesson 4: Combining HTML5 and JavaScript in Web Applications


Chapter 4 - Page 3
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
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
Every time you modify code in n Edit area,
the
aRun S t if you think you have written the solution for
u s
one of the practices, clickkthe i s
button
h and see the result in the Preview Results area.
ฺ v e t
The Revert Changes
i l an button u sreplaces the current content with the original content of the
file.
n to
(mbutton opens
k s a
The Solution a window with the code for all practices.
TheuPreview Results area contains the HTML elements to manipulate, as shown in the
V graphic:
nfollowing
a
Mil

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

Practices for Lesson 4: Combining HTML5 and JavaScript in Web Applications


Chapter 4 - Page 4
After adding some code in the Edit area, click the Run button, as shown in the following
graphic:
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
o n -tr
The Preview Results area is refreshed, as shown in the followingn graphic:
a
s eฺ
h a
ฺ r s ) u id
e ms dent G
a n @ Stu
ฺ v uks e this
m i lan to us
n (
ks a
u
V the necessary code in the Edit area for all practices. Instructions for the practices are on
Add
anthe Instructions tab, next to the Preview tab, as shown in the following graphic:
Mil

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

Practices for Lesson 4: Combining HTML5 and JavaScript in Web Applications


Chapter 4 - Page 5
After completing the practices, click the Back button to go to the main page.

Task
Based on the overview steps detailed in the preceding section, complete the practices
under “Practice: Manipulate HTML elements” for the lesson titled “Combining HTML5 and
JavaScript in Web Applications” on the main page of JConsole, as shown in the following
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

graphic:

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

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

Practices for Lesson 4: Combining HTML5 and JavaScript in Web Applications


Chapter 4 - Page 6
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
o n -tr
Practices afor n Lesson 5: The
JavaScript
h s
a dAPIeฺ
)
ฺrs 5t Gu i
s
Chapter
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 1
Practices for Lesson 5: Overview
Practice Overview
In these practices, you parse and manipulate form input in an HTML5 application.
The application is a tip calculator based on the age of the people. Older people pay more than
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

younger people, proportional to their age.


Practice 5-2 is optional, and provides a higher level of difficulty. You must complete practice 5-1
before starting 5-2.
These practices can be performed in your own environment by using NetBeans 8.

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

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 2
Practice 5-1: Bill Calculator by Age
Overview
In this practice, you create the JavaScript code that is required to calculate how the bill is
divided based on the age of people.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Tasks
1. Double-click the NetBeans 8 icon on your desktop to open it.
2. Select File > New Project.

n s e
i ce
b l el
fer a
3. Select the HTML5 category and the HTML5 Application project. Click Next.
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

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 3
4. Enter lab_05_01 as the project name and browse to
/home/oracle/labs/activities/ for Project Location. Click Finish.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

An empty project is created with no templates, libraries, or external resources.


5. By default, the index.html file is displayed in the editor. If this is not the case, open it by
double-clicking it on the Projects tab.

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

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 4
6. Edit the index.html file to match the following code. The new code is highlighted in bold:
<!DOCTYPE html>
<html>
<head>
<title>Tip Calculator</title>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<script src="code.js"></script>
</head>
<body>
<h1>Tip Calculator</h1>
<ul id="personList"> n s e
i ce
<li>
b l el
Name:
fer a
<input type="text" name="name"/>
a n s
Age:
n - tr
o
an
<input type="text" name="age" size="2"/>
s
</li>
) h a deฺ
</ul>
s ฺrs t Gui
em uden
<a href="#" id="addTip">[+] Add more</a><br/>
@
<br/>
a n S t
s
uk e thi s
Bill total:<input type="text" id="billTotal" size="5"/>
ฺ v
an
Tip:
s
n (mil to u
<input type="text" id="tipPercent" size="2" value="10"/>%

ksa
<br/>

V u <input id="calculateButton" type="button" value="Calculate"/>


an
Mil
<div id="outputDiv">
</div>
</body>
</html>
7. Right-click Site Root and select New > JavaScript File.

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 5
8. Enter code as File Name and click Finish.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

9. Open the code.js file.


10. Add the following code to add the basic window and element listeners.
window.addEventListener("load", function() {
n s e
var listElement = document.getElementById("personList");
i ce
document.getElementById("addTip")
b l el
.addEventListener("click", function() {
fer a
//Add new element with remove button.
a n s
}); n - tr
o
document.getElementById("calculateButton")
s an
h a deฺ
.addEventListener("click", function() {
)
ฺrs t Gui
var outputElem = document.getElementById("outputDiv");
s
em uden
//Array of Person objects
@
var result = [];
a n S t
s
uk e thi s
var personElements = listElement.getElementsByTagName("li");
ฺ v
an s
// Parse elements and calculate total per person.

n (mil to u
outputElem.innerHTML = result.join("<br>");

u ksa });

n V });
a
Mil Comments are used to locate where to add code in subsequent steps.

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 6
11. Add the following code to add the Person constructor and the toString function:
function Person() {
this.name = "";
this.age = 1;
this.bill = 0;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Person.prototype.toString = function() {
// Change for better string representation of numbers.
var billString = this.bill.toString();
return this.name + "[" + this.age + "] pays " + billString;
};
n s e
12. Right-click the lab_05_01 project and select Run from the menu.
i ce
b l el
fer a
a n s
o n -tr
s an
) h a deฺ
s ฺrs t Gui
m den
eclose
n @
If you make changes to the project
a or
S tuthe web browser, you can use the run
u s ethethnew
command to open it againkwith
ฺ v is changes.
m i lan to us
n (
a
V uks
an
Mil

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 7
Create input fields when the user clicks the “add person” link.
13. Locate the “//Add new element with remove button.” comment and add the
following code below it to create a new person list element:
var newElement = listElement
.getElementsByTagName("li")[0].cloneNode(true);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

listElement.appendChild(newElement);
14. Add the following code to add the remove button:
var removeButton = document.createElement("input");
removeButton.setAttribute("type", "button");
removeButton.setAttribute("value", "remove");
newElement.appendChild(removeButton);
15. Enter the following code to add the remove behavior: n s e
i ce
removeButton.addEventListener("click", function() {
b l el
listElement.removeChild(newElement);
fer a
});
a n s
n -tr
Your completed function should look similar to the following:
o
a n
document.getElementById("addTip").addEventListener("click",
function() {
h s
a deฺ
var newElement = listElementrs
ฺ ) ui
s
m dent G
e
.getElementsByTagName("li")[0].cloneNode(true);
@ Stu
var removeButton =ndocument.createElement("input");
a
ks this
ฺ v u
removeButton.setAttribute("type", "button");

i l a n use
removeButton.setAttribute("value", "remove");
(m to
removeButton.addEventListener("click",
n
function() {
a listElement.removeChild(newElement);
V uks });
l a n
Mi
newElement.appendChild(removeButton);
listElement.appendChild(newElement);
});
Note that clicking add will add a new row with inputs by duplicating the existing inputs. This
will duplicate the values inside the inputs as well.

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 8
Parse person fields.
To parse the form and calculate the bill total, add the following code below the // Parse
elements and calculate total per person comment.
16. Create a new totalAge variable to add the ages of the people.
var totalAge = 0;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

17. Iterate the elements inside the HTML5 list with the following:
for (i = 0; i < personElements.length; i++) {
18. Inside the for-loop, get the input elements by using the following code:
var inputElements = personElements[i]
.getElementsByTagName("input");
19. Create a new person object by entering the following code:
n s e
i ce
el
var person = new Person();
20. Iterate the input elements by using the following loop:
a b l
fer
for (j = 0; j < inputElements.length; j++) {
a n s
o n -tr
21. Check the name of the current input element. If the name is "name", set person.name to

s an
the value of the input element. If the name is "age", set person.age to be the parsed
value of the input element and add the age to the totalAge variable.
) h a { deฺ
if (inputElements[j].name === "name")
s ฺ r s Gui
m dent
person.name = inputElements[j].value;
e
}
a n @ Stu
k s his === "age") {
if (inputElements[j].name
u
n e t
person.ageฺv= parseInt(inputElements[j].value);
s
ila +=toperson.age;
u
}an
( m
totalAge

22. k s
uPush the person object in the result array.
n V
a
Mil result.push(person);

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 9
Use the following code for the function as reference:
var outputElem = document.getElementById("outputDiv");
var result = [];
var personElements = listElement.getElementsByTagName("li");
var totalAge = 0;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

for (i = 0; i < personElements.length; i++) {


var inputElements = personElements[i]
.getElementsByTagName("input");
var person = new Person();
for (j = 0; j < inputElements.length; j++) {
if (inputElements[j].name === "name") {
person.name = inputElements[j].value;
n s e
}
i ce
if (inputElements[j].name === "age") {
b l el
person.age = parseInt(inputElements[j].value);
fer a
totalAge += person.age;
a n s
} n - tr
o
}
s an
result.push(person);
) 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

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 10
Calculate the total value to pay for the bill.
23. Parse the element with the Id "billTotal". This contains the total of the bill.
var billValue = parseFloat(document
.getElementById("billTotal").value);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

24. Parse the element with the Id "tipPercent". This contains the percent to tip.
var tipPercent = parseInt(document
.getElementById("tipPercent").value);
25. Calculate the total of the bill with the tip by using the following formula:
totalWithTip=total+(total*(tipPercent/100))
var totalBill = billValue + (billValue * (tipPercent / 100));
26. Divide the bill by the totalAge variable, which contains the sum of the ages.
n s e
var partialBill = totalBill / totalAge; li ce
l e
b to
e r a
27. Iterate the result array and for each person object in the result array, set the bill property
be equal to partialBill times the result[i].age property.
a n sf
for (i = 0; i < result.length; i++) {
o n -tr
an
result[i].bill = partialBill * result[i].age;
}
h s
a deฺ
28. Use the following code for reference:
ฺ )
rs t Gui
s
em uden
var billValue = parseFloat(document
@
an is St
.getElementById("billTotal").value);
var tipPercent =ks
vu se th
parseInt(document
n ฺ
ila to= ubillValue + (billValue * (tipPercent / 100));
.getElementById("tipPercent").value);
( m
var totalBill

k s an partialBill = totalBill / totalAge;


var
V u for (i = 0; i < result.length; i++) {
an
Mil
result[i].bill = partialBill * result[i].age;
}
29. Change the toString method of the person prototype to display the bill value in currency
format.
var billString = this.bill.toLocaleString("en-US", {style:
"currency", currency: "USD", maximumFractionDigits: 2});
30. Save the file and run the project again.

You can check the solved version of the code.js file in the following folder:
/home/oracle/labs/solutions/lab_05_01

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 11
Practice 5-2 (Optional): Changing Inputs for Birth Dates
Overview
In this practice, you modify the HTML form, replacing the age input with multiple inputs to
handle and parse dates. Based on these dates, you calculate the age of the people to divide the
tip.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Assumption
You have completed Practice 5-1.

Tasks
1. Open the index.html file.
2. Replace the age input with three new inputs: day, month, and year.
3. Open the code.js file. n s e
i ce
4. Modify the person function and add the birthdate property with a value of
b l el
Date.now().
fer a
5. Optional: Set milliseconds, seconds, minutes, and hours to 0.
a n s
6. -tr
Modify the toString Person.prototype function to output the birthdate property.
o n
7. In the click event of the calculate button, add a now variable
a nwith the value new Date()
after the totalAge variable.
h s
a deฺ
8. Replace the parsing of the age input element )
ฺrswithtthree i
uconditions for date inputs.
s G
em uden with the value from the day
 Set the day by using person.birthdate.setDate
@
element.
s an is St
 Set the month by usingkperson.birthdate.setMonth with the value from the month
element minus n 1.ฺv
u e th
i lby u s
a usingoperson.birthdate.setFullYear
( m
 Set the year t with the value from the

k s anelement.
year

V 9. uSet person.age to now.getFullYear() - person.birthdate.getFullYear().


l a n 10. Optional: Validate that person.birthdate is not greater than the current value in order to
Mi prevent negative values.
11. Optional: Validate that person.birthdate has passed in the current year to calculate the
age correctly.
The solution for this challenge is on the next page.

You can check the solved version of the code.js and index.html files in the following folder:
/home/oracle/labs/solutions/lab_05_02

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 12
Solution 5-2: Changing Inputs for Birth Dates
Person Function:
function Person() {
this.name = "";
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

this.birthdate = new Date();


this.birthdate.setMilliseconds(0);
this.birthdate.setHours(0);
this.birthdate.setMinutes(0);
this.birthdate.setSeconds(0);
this.bill = 0;
}
n s e
i ce
Person.prototype.ToString Function:
b l el
Person.prototype.toString = function() {
fer a
var billString = this.bill.toLocaleString("en-US", {
a n s
o n -tr
style:"currency", currency:"USD", maximumFractionDigits:2});

an
var dateString = this.birthdate.toLocaleString("en-US");
s
var result = this.name+" "+this.age;
) h a deฺ
ฺrs t Gui
result = result +"["+dateString+"] pays "+billString;
s
return result;
@ em uden
};
a n S t
s
uk e thi s
Parsing Inputs: ฺ v
m i lan to us
if (inputElements[j].name === "day") {
n (
k s aperson.birthdate.setDate(parseInt(inputElements[j].value));
V u }
an if (inputElements[j].name === "month") {
Mil person.birthdate.setMonth(parseInt(inputElements[j].value)-1);
}
if (inputElements[j].name === "year") {
person.birthdate.setFullYear(parseInt(inputElements[j].value));
}

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 13
Calculating and Validating Age:
if (person.birthdate.getTime() > now.getTime()) {
alert("Invalid birthdate!");
return;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

}
person.age = now.getFullYear() - person.birthdate.getFullYear();
var thisYearBD = new Date(person.birthdate.getTime());
thisYearBD.setFullYear(now.getFullYear());
if (thisYearBD > now) {
person.age--;
}
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

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

Practices for Lesson 5: The JavaScript API


Chapter 5 - Page 14
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
o n -tr
Practices afor n Lesson 6: Web
s eฺ
a dData
Application
h
)
ฺrs 6t Gu i
s
Chapter
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 1
Practices for Lesson 6: Overview
Practice Overview
In these practices, you create a to-do application that persists tasks by using local storage.
These practices can be performed in your own environment by using NetBeans 8.
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

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 2
Practice 6-1: Creating a To-Do Application with Local Storage
Overview
In this practice, you create a to-do application that saves the list of tasks by using local storage
and JSON.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Tasks
1. Open NetBeans 8.
2. Select File > New Project from the menu.
3. Select the HTML5 category and the HTML 5 Application project. Click Next.

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 4. Name the project lab_06_01 and check whether the project location is
/home/oracle/labs/activities. Click Finish.
5. Modify the index.html file and add the following code to the body tag:
<h1>To Do List</h1>
<ul id="toDoList"></ul>
<h2>Add New item</h2>
<input type="text" name="taskTitle" id="taskTitle">
<input type="button" id="addNew" value="Add"/>
6. Add the following code to <head> of the HTML file to load the JavaScript file.
<script type="text/javascript" src="code.js"></script>
7. Right-click the Site Root node on the Projects tab and select New > JavaScript File.
8. Set the name to code and click Finish.
9. Open the code.js file if it is not already open.

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 3
10. Add the following function to create a Task object constructor:
function Task(title) {
this.title = title;
this.done = false;
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

11. Create a new array to contain all the tasks.


var allTasks = [];
12. Add a new window onload listener.
window.addEventListener("load", function() {
});
13. Inside the listener, add the following to load the saved tasks:
var loadedTasks = JSON.parse(localStorage.getItem("tasks")); n s e
i ce
if (!loadedTasks) {
b l el
loadedTasks = [];
fer a
}
a n s
o n -tr
14. For each of the loaded tasks, invoke a function to add the task to the application. You

a {n
create this function in a later step.
for (i = 0; i < loadedTasks.length; ai++)
h s eฺ
) i d
addTask(loadedTasks[i]);
s ฺrs t Gu
}
@ em u d n
enew
a n
15. Add functionality to the addNewButton to
S t
add a task to the to-do list.
 Get the button by ID. ks is
ฺ v u t h
i l a n use
 Add a click listener.
m element.
 Get the(taskTitle
n to
u k sa a new Task object by using the taskTitle value.
 Create

an V  Invoke the addTask function for each of the tasks.


Mil  Optionally, erase the contents of the taskTitle input by setting its value to “”.
var addNewButton = document.getElementById("addNew");
addNewButton.addEventListener("click", function() {
var titleInput = document.getElementById("taskTitle");
var task = new Task(titleInput.value);
addTask(task);
titleInput.value = "";
});
16. Create the addTask function.
function addTask(task) {
}
17. Add the task to the allTasks array.
allTasks.push(task);

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 4
18. Obtain the toDoList ul element.
var listContainer = document.getElementById("toDoList");
19. Create a new li element.
var taskNode = document.createElement("li");
20. Create the check box element.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var checkbox = document.createElement("input");


checkbox.setAttribute("type", "checkbox");
if (task.done) {
checkbox.setAttribute("checked", "checked");
}
21. Add a change listener to the check box element.
 Set task.done to !task.done to toggle the done property. n s e
i ce
 Check whether the task is done.
b l el
 If it is done, add a checked=checked attribute to the check box element.
fer a
 If it is not done, remove the checked attribute from the check box element.
a n s
o n -tr
 Call the save function. You write this function in a later step.

an {
checkbox.addEventListener("change", function()
s
task.done = !task.done;
) h a deฺ
if (task.done) {
s ฺrs t Gui
em uden "checked");
checkbox.setAttribute("checked",
@
} else {
a n S t
s
uk e thi s
checkbox.removeAttribute("checked");
ฺ v
}
m i lan to us
(
save();
n
a
uks
});
V
22. Append the check box to taskNode.
an
Mil taskNode.appendChild(checkbox);
23. Create a text node with the task.title value and append it to taskNode.
var text = document.createTextNode(task.title);
taskNode.appendChild(text);
24. Create a delete button input element.
var deleteButton = document.createElement("input");
deleteButton.setAttribute("type", "button");
deleteButton.setAttribute("value", "Remove");

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 5
25. Add a click listener to the delete button.
 Iterate the allTasks array.
 If the iterated element is equal to the task, remove it from the allTasks array by using
the splice(index, 1) function and break the iteration.
 Remove taskNode from listContainer.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

 Call the save function.


deleteButton.addEventListener("click", function() {
for (index = 0; index < allTasks.length; index ++) {
if (allTasks[index] === task) {
allTasks.splice(index, 1);
break;
}
n s e
}
i ce
listContainer.removeChild(taskNode);
b l el
save(); fer a
a n s
-tr
});
26. Append the delete button to taskNode.
n o n
taskNode.appendChild(deleteButton); s a
) h a deฺ
27. Append taskNode to listContainer.
s ฺ rs t Gui
em uden
listContainer.appendChild(taskNode);
@
28. Invoke the save function.
a n S t
s
uk e thi s
save();

n usv
i
29. Create the save
m lafunction.
to {
n ( save()
ksa localStorage.setItem("tasks", JSON.stringify(allTasks));
function
u
anV }
Mil 30. Run the application and test the functionality.
You can check the solved version of the code.js file in the following folder:
/home/oracle/labs/solutions/lab_06_01

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 6
Practice 6-2 (Optional): Adding a Remove Completed Tasks Button
Overview
In this practice, you add a button to remove the completed tasks.

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

You finished Practice 6-1.

Tasks
1. Open the index.html file.
2. Add the input button.
3. Open the code.js file.
4. Add an ID field to the Task object.
n s e
5. Add a lastId global variable. i ce
6. In the addTask method, set task.id = lastId++. b l el
7. Set the ID of the li element to "task"+task.id. fer a
a n s
8.
9. o n -tr
Add the click listener to the button inside the load listener for the window.
Iterate the tasks, and if the task is completed, add it to a temporal array to remove it in
another loop.
s an
h a deฺ
This is done because removing items while iterating them can lead to unstable behavior.
)
ฺrs t Gui
You create another array to iterate it and remove items from the allTasks array.
s
em uden
10. Iterate the newly created array that contains the tasks to remove the elements from the
@
n t
allTasks array. Using the task.id, locate the li element and remove it from the
a S
toDoList element. s
uk e thi s
ฺ v
i l an o us
11. Call the save function.
m t
12. Optionally,(create a removeTask
n method to remove duplicate code from the “remove” and
a
ks for this challenge is on the following page:
“remove all completed” buttons.
u
nV
The solution
a
Mil You can check the solved version of the code.js file in the following folder:
/home/oracle/labs/solutions/lab_06_02

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 7
Solution 6-2: Removing Completed Tasks

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

<!DOCTYPE html>
<html>
<head>
<title>TO DO List</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<script type="text/javascript" src="code.js"></script> n s e
i ce
</head>
b l el
<body>
fer a
<h1>To Do List</h1>
a n s
<ul id="toDoList">
n - tr
o
an
</ul>
s
a deฺ
<input type="button" id="removeCompleted" value="Remove
h
Completed Tasks"/> )
ฺrs t Gui
<h2>Add New item</h2> s
@ em uden
<input type="text" name="taskTitle" id="taskTitle">
a n S t
s s
<input type="button" id="addNew" value="Add"/>
uk e thi
</body> ฺ v
an s
</html>
n (mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 8
code.js file:
function Task(title) {
this.title = title;
this.done = false;
this.id = 0;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var allTasks = [];


var lastId = 0;

window.addEventListener("load", function() {
//Get from local storage JSON.
n s e
var loadedTasks = JSON.parse(localStorage.getItem("tasks"));
i ce
if (!loadedTasks) {
b l el
loadedTasks = [];
fer a
}
a n s
for (i = 0; i < loadedTasks.length; i++) {
n - tr
o
addTask(loadedTasks[i]);
s an
}
) h a deฺ
ฺrs t Gui
var addNewButton = document.getElementById("addNew");
s
em uden
addNewButton.addEventListener("click", function() {
@
n t
var titleInput = document.getElementById("taskTitle");
a S
s
uk e thi s
var task = new Task(titleInput.value);
ฺ v
an
addTask(task); s
n (mil to u
titleInput.value = "";

ksa
});
V u var removeCompletedButton =
an
Mil
document.getElementById("removeCompleted");
removeCompletedButton.addEventListener("click", function() {
var taskToRemove = [];
for (i = 0; i < allTasks.length; i++) {
if (allTasks[i].done) {
taskToRemove.push(allTasks[i]);
}
}
for (j = 0; j < taskToRemove.length; j++) {
removeTask(taskToRemove[j]);
}
});
});

function addTask(task) {

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 9
allTasks.push(task);
task.id = lastId++;
var listContainer = document.getElementById("toDoList");

var taskNode = document.createElement("li");


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

taskNode.setAttribute("id", "task" + task.id);

var checkbox = document.createElement("input");


checkbox.setAttribute("type", "checkbox");
if (task.done) {
checkbox.setAttribute("checked", "checked");
}
n s e
ce
checkbox.addEventListener("change", function() {
eli
task.done = !task.done;
a b l
if (task.done) {
fer
checkbox.setAttribute("checked", "checked");
a n s
} else {
o n -tr
an
checkbox.removeAttribute("checked");
s
}
) h a deฺ
save();
s ฺrs t Gui
});
@ em uden
n t
taskNode.appendChild(checkbox);
a S
s
uk e thi s
var text n=ฺvdocument.createTextNode(task.title);
m i la to us
(
taskNode.appendChild(text);
n
k s a
V u var deleteButton = document.createElement("input");
an
Mil
deleteButton.setAttribute("type", "button");
deleteButton.setAttribute("value", "Remove");
deleteButton.addEventListener("click", function() {
removeTask(task);
save();
});
taskNode.appendChild(deleteButton);

listContainer.appendChild(taskNode);
save();
}

function removeTask(task) {
var listContainer = document.getElementById("toDoList");

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 10
var taskNode = document.getElementById("task" + task.id);
for (i = 0; i < allTasks.length; i++) {
if (allTasks[i] === task) {
allTasks.splice(i, 1);
break;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

}
}
listContainer.removeChild(taskNode);
save();
}

function save() {
n s e
ce
localStorage.setItem("tasks", JSON.stringify(allTasks));
eli
}
a b l
fer
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

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 11
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

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

Practices for Lesson 6: Web Application Data


Chapter 6 - Page 12
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
o n -tr
Practices afor n Lesson 7: Style
Applications
h s ฺ
a deUsing CSS3 and
)
ฺrs t Gu
JavaScript
i
s
@ em Chapter
u d en7
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 7: Style Applications Using CSS3 and JavaScript


Chapter 7 - Page 1
Practices for Lesson 7: Overview
Practices Overview
In the practices for this lesson, you write CSS rules to get the requested style.
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

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

Practices for Lesson 7: Style Applications Using CSS3 and JavaScript


Chapter 7 - Page 2
Practice 7-1: Styling Elements with CSS3
Overview
In this practice, you write CSS rules to style elements in the document.
The practice for this lesson is located in the web application JSConsole. You can access it by
navigating to http://localhost:8080/JSConsole/ in your browser. There, you add the necessary
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

code to style elements in the web document as required.


The next graphic shows a part of the main page of JSConsole:

n s e
i ce
b l el
fer a
a n s
o n -tr
a n
The pencil symbol button leads to the practice itself. a
h s eฺ code there to style the
You add the
) i d
HTML elements.
s ฺrs file.t G u
em uindthe
The play symbol button leads to the index.html
@ enEdit area to get the behavior requested
After opening the practice, you can n
for the HTML elements located s ina
edit tResults area. The following graphic shows the
the code
S
main components on thisฺv uk e thi
screen:
s
the Preview

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

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

Practices for Lesson 7: Style Applications Using CSS3 and JavaScript


Chapter 7 - Page 3
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
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk thethEditi s
Every time you modify
n ฺ vcode ine
s area, if you think you have written the solution for
i l a
one of the practices, click
o u
the Run button and see the result in the Preview Results area.
( m t
n Changes button replaces the current content with the original content of the
The Revert
k s
file. a
VuThe Solution button opens a window with the code for all practices.
an
Mil The Preview Results area contains the HTML elements to style (in this case, paragraphs
<p> and images <img>), as shown in the following graphic:

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

Practices for Lesson 7: Style Applications Using CSS3 and JavaScript


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

n s e
i ce
b l el
After adding some code in the Edit area, click the Run button as shown in the following graphic:
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
The Preview Results area is refreshed, as shown in the following graphic:

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

Practices for Lesson 7: Style Applications Using CSS3 and JavaScript


Chapter 7 - Page 5
Add the necessary code in the Edit area for all practices. For most of the practices, you will
need to clear the current content in the Edit area by clicking the Revert Changes button before
going to the next practice.
Instructions for the practices are on the Instructions tab, next to the Preview tab, as shown in
the following graphic:
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
o n -tr
n
a main
After completing the practices, click the Back button to go to
h a s the
e ฺ page.

ฺ r s ) u id
Task s nt G
Based on the overview steps detailedeinm
n
under “Practice: Styling Elements” @ t u
for the lesson
detitled “Style
the preceding section, complete the practices
Applications using CSS3 and
s a s S
ฺ v uk e thi
JavaScript” on the main page of JConsole, as shown in the following graphic:

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

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

Practices for Lesson 7: Style Applications Using CSS3 and JavaScript


Chapter 7 - Page 6
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
o n -tr
Practices afor n Lesson 8:
Advancedh s eฺ
a JavaScript
) i d
s ฺrs 8t Gu
Chapter
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n ( mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 1
Practices for Lesson 8: Overview
Practices Overview
In these practices, you create a simple application to paint in the HTML5 canvas element by
using HTML input buttons and drag-and-drop and mouse gestures.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

After you finish Practice 8-1, you can try any of the other practices in any order. Each practice
focuses on the following topics:
• Practice 8-2: Intervals and Timers
• Practice 8-3: Drag and Drop
• Practice 8-4: Mouse Events

These practices can be performed in your own environment by using NetBeans 8. Stickers from n s e
i ce
Practice 8-3 can be substituted by any other image. The stickers that are provided are
transparent .png images with 100 pixels height. 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

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

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 2
Practice 8-1: Painting in an HTML5 Canvas Element
Overview
In this practice, you create the HTML5 canvas application with buttons that draw and clear the
canvas.
After you have completed, your application should look similar to the following:
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
o n -tr
s an
) h a deฺ
ฺrs t Gui
Tasks
1. Open NetBeans 8. s
em uden
2. Select File > New Project from the menu.
@
3. Select the HTML5 categorysanda nthe HTML
S t5 Application project. Click Next.
uk e thi s
ฺ v
m i lan to us
n (
ks a
V u
an
Mil

4. Name the project lab_08_01 and check whether the project location is
/home/oracle/labs/activities. Click Finish.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 3
5. Modify the index.html file:
 Change the title of the page to HTML5 Canvas and JavaScript.
 Add a script reference to code.js in the <head> section of the file.
 Inside the body, add a div element with a “palette” Id.
 Inside the palette div element, add two buttons.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

 A “clear” button that has an onclick event that calls the clearCanvas()
JavaScript function
 A “circle” button that has an onclick event that calls the drawCircle() JavaScript
function
 Add another div element with a “content” ID.
 Inside content div, add a canvas element with a “board” Id, a width property of 640, and
a height property of 480.
 Optionally, add a div element that encloses the canvas element and add a style attribute n s e
i ce
to add a border to the canvas.
b l el
Use the following code for reference:
fer a
<!DOCTYPE html>
a n s
<html>
n - tr
o
an
<head>
s
a deฺ
<title>HTML5 Canvas and JavaScript</title>
h
<meta charset="UTF-8"> )
ฺrs t Gui
s
em uden
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
a n @ S t
s s
<script src="code.js" type="text/javascript"></script>
uk e thi
</head> ฺ v
an s
mil to u
<body>
n (
<div id="palette">

u ksa <input type="button" value="clear" onclick="clearCanvas()"/>


n V <input type="button" value="circle" onclick="drawCircle()"/>
a
Mil </div>
<div id="content">
<div style="border:1px solid black; width:640px">
<canvas id="board" width="640" height="480"></canvas>
</div>
</div>
</body>
</html>
6. Right-click the Site Root node on the Projects tab and select New > JavaScript File.
7. Set the name to code and click Finish.
8. Open the code.js file if it is not already open.
9. Add a global canvas variable declaration.
var canvas;
10. Add a window load listener and assign to the canvas variable the value of:
document.getElementById("board");
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 4
window.addEventListener("load", function() {
canvas = document.getElementById("board");
});
11. Create a new clearCanvas function.
 Get the 2d context of the canvas element and assign it to a new variable named ctx.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

 Assign to the fillStyle property of ctx the value "#FFFFFF" to set the fill color to
solid white.
 Call the fillRect function in the canvas element to paint the entire canvas.
Use the following code for reference:
function clearCanvas() {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FFFFFF";
n s e
ce
ctx.fillRect(0, 0, canvas.width, canvas.height);
eli
}
a b l
12. Create the drawCircle function.
fer
 Get the 2d context of the canvas element and assign it to a new variable named ctx.
a n s
n -
 Assign to the strokeStyle property of ctx the value of "#000000" to set the stroke tr
o
to black.
s an
 Call ctx.beginPath to start a path.
) h a deฺ
 Create an arc in the middle of the canvas.
s ฺrs t Gui
em uden
 The x coordinate is equal to canvas.width/2.
@
 The y coordinate is equaln
a t
to canvas.height/2.
S
 The radius is set u to k
s hi s
ฺ v
n is 0.us
45.
e t
 The initial
m i laangle o
 The (final angle ist 2*Math.PI.
n
sa ctx.stroke to paint the circle on screen.
 kCall
u
V Use the following code for reference:
an
Mil function drawCircle() {
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "#000000";
ctx.beginPath();
var width = canvas.width / 2;
var height = canvas.height / 2;
ctx.arc(width, height, 45, 0, 2 * Math.PI);
ctx.stroke();
}
13. Run the application and click the buttons. A circle is drawn with the “circle” button and the
canvas is cleared to a white color when the “clear” button is clicked.

You can check the solved version of the code.js and index.html file in the following folder:
/home/oracle/labs/solutions/lab_08_01

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

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 5
Practice 8-2: Creating an Interval to Paint in a Canvas Element
Overview
In this practice, you create an interval function to paint dots in the canvas element in random
positions.
After you have finished, your application will have an extra button that paints circles in random
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

positions at a fixed interval when it is first clicked and stops the interval when it is clicked again.

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

Assumptions
You have finished practice 8-1.

Tasks
1. Open the index.html file.
2. Add an input button inside the <div id="palette"> element and set its onclick event
to the drawDots() JavaScript function.
<input type="button" value="dots" onclick="drawDots()"/>
3. Open the code.js file.
4. Create a global variable named lastInterval to store the Id of the current interval. Do
not set any value to it.
var lastInterval;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 6
5. Create the drawDots function.
function drawDots() {
6. Check whether the lastInterval variable is defined and invoke
clearInterval(lastInterval). Then unset the lastInterval variable.
if (lastInterval) {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

clearInterval(lastInterval);
lastInterval = undefined;
7. Add an else statement.
} else {
8. Assign to the lastInterval variable the result from calling the setInterval() function
with an anonymous function as a parameter.
lastInterval = setInterval(function() {
9. Inside the anonymous function: n s e
 Get the 2d context from the canvas and assign it to a new ctx variable li ce
b l e
 Set the ctx.strokeStyle="#000000" and ctx.fillStyle="#AAAAAA"
e r aproperties
 Invoke ctx.beginPath();
a n sf
 Create an x variable for the “x” position and assign a random n
o -tr between 0 and
value
canvas.width to it
a n
 Create a y variable for the “y” position and assigna
h s ฺ between 0 and
a randomevalue
) i d
canvas.height to it
s ฺrs by using
t G u
 Invoke the ctx.arc function to draw
e m den the x, y coordinates and a radius
a circle
of 10
a n @ Stu
 Call ctx.fill to create
v u ksa solidthcolor
is circle
 Call ctx.stroke
a ฺ sethe circle
n to outline
i l to u
m = canvas.getContext("2d");
(
var ctx
n
a
uksctx.fillStyle = "#AAAAAA";
ctx.strokeStyle = "#000000";
V
an
Mil
ctx.beginPath();
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
ctx.arc(x, y, 10, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
10. Close the anonymous function and set a second parameter to the setInterval function
to the number of milliseconds that the interval function will be invoked.
}, 250);
11. Close the else statement and function declaration.
}
}
12. Test the application. Clicking the dots button will make dots appear in the canvas. Clicking
the button again will stop the dots from appearing.

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

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 7
You can check the solved version of the code.js and index.html files in the following folder:
/home/oracle/labs/solutions/lab_08_02
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

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

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 8
Practice 8-3: Implementing Drag and Drop to Paint Images on the
Canvas
Overview
In this practice, you create image elements that can be dragged over the canvas to paint them.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

After you have finished, you can drag and drop stickers to the canvas.

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

Assumptions
You have finished Practice 8-1.

Tasks
1. Copy the images from the /home/oracle/labs/resources/stickers folder to the
/home/oracle/labs/activities/lab_08_01/public_html folder.
2. Open the index.html file.
3. Add one or multiple img elements inside <div id="palette">.
4. For each img element:
 Set the src attribute to one of the sticker images that you copied in step 1
 Set the draggable attribute to true.
 Set the ondragstart event to the drag(event) JavaScript function.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 9
 Set the Id of the element to something unique such as sticker1, sticker2, and so
on. Make sure that you do not repeat the Ids of the img elements.
 Set the alt attribute to something descriptive. You may leave this attribute empty.
Use the following code for reference:
<img src="sticker1.png" draggable="true"
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

ondragstart="drag(event)" id="sticker1" alt="">


5. Modify the canvas element.
 Set the ondrop event to the drop(event) JavaScript function.
 Set the ondragover event to the allowDrop (event) JavaScript function.
Use the following code for reference; the added attributes are highlighted in bold.
<canvas id="board" width="640" height="480" ondrop="drop(event)"
ondragover="allowDrop(event)"></canvas>
6. Open the code.js file. n s e
7. Create the drag(event) function. li ce
b l e
 Get the Id of the dragged element by using event.target.getAttribute("id").
e r a
f is sent from
 In drag-and-drop interactions, you store a value in a data transfer object
a n sthat
Invoke event.dataTransfer.setData("text", elementId) o -tar drop.
the element that starts the drag to all the objects that can receive
n to set the Id of the
a
dragged element as the transferred data of the drag-and-drop
n interaction.
h a s eฺ
Use the following code for reference:
ฺ r s ) u id
ms dent G
function drag(event) {
e
var elementId = event.target.getAttribute("id");
@ Stu
s a n
event.dataTransfer.setData("text", elementId);
k i s
}
n ฺ vu se th
8. ila to u function.
Create the allowDrop(event)
( m
 The nallowDrop function is called with the ondragover event. By default, this event
s a
V event.preventDefault();. ukprevents drop operations. To allow this operation, you must call

a n
Mil Use the following code for reference:
function allowDrop(event) {
event.preventDefault();
}
9. Create the drop(event) function.
 The drop function is executed when the cursor is released. By default, the drop
operation does nothing, and is not allowed. To allow the operation, call
event.preventDefault() as the first statement of the function.
 To get the Id of the element that was dragged, get the data you stored in the drag
function by using event.dataTransfer.getData("text");.
 Get the <img> element by using the Id that you just retrieved from the data transfer.
 Get the 2d context of the canvas element.
 Get the bounds of the canvas by using canvas.getBoundingClientRect();.
 Calculate the X coordinate by using event.clientX - canvasBounds.left;.
 Calculate the Y coordinate by using event.clientY - canvasBounds.top;.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 10
 Invoke ctx.drawImage by using the <img> element and the x, y coordinates as
parameters.
Use the following code for reference:
function drop(event) {
event.preventDefault();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var elementId = event.dataTransfer.getData("text");


var element = document.getElementById(elementId);
var ctx = canvas.getContext("2d");
var canvasBounds = canvas.getBoundingClientRect();
var x = event.clientX - canvasBounds.left;
var y = event.clientY - canvasBounds.top;
ctx.drawImage(element, x, y);
} n s e
i ce
10. Run the application and drag-and-drop the images onto the canvas. Note that the images
are drawn in the canvas when they are dropped. b l el
fer a
a n s
You can check the solved version of the code.js and index.html files in the following folder:
n - tr
/home/oracle/labs/solutions/lab_08_03 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

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

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 11
Practice 8-4: Painting the Canvas with Mouse Gestures
Overview
In this practice, you create mouse events for the canvas element to simulate the effect of
painting with a paintbrush.
After you have finished, clicking and dragging your mouse will paint as a paintbrush.
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
Assumptions
You have finished Practice 8-1.

Tasks
1. Open the index.html file.
2. Modify the canvas element.
 Set the onmousedown event to the mouseDown(event) JavaScript function.
 Set the onmousemove event to the mouseMove(event) JavaScript function.
 Set the onmouseup event to the mouseUp(event) JavaScript function.

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

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 12
Use the following code for reference; the added attributes are highlighted in bold.
<canvas id="board" width="640" height="480" ondrop="drop(event)"
ondragover="allowDrop(event)" onmousedown="mouseDown(event)"
onmousemove="mouseMove(event)" onmouseup="mouseUp(event)">
</canvas>
3. Open the code.js file.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

4. Create a new global variable isdown and set it to false. This variable is used to know
whether the mouse button is pressed on the canvas or not.
var isdown = false;
5. Create the mouseDown(event) function.
 Set the isdown variable to true.
Use the following code for reference:
function mouseDown(event) {
n s e
i ce
el
isdown = true;
}
a b l
6. Create the mouseUp(event) function. fer
a n s
 Set the isdown variable to false.
Use the following code for reference: o n -tr
function mouseUp(event) { s an
) h a deฺ
ฺrs t Gui
isdown = false;
} s
7. Create the mouseMove(event) function.
@ em uden
s a n whenSthet isdown variable is set to true because you
 This function paints the canvas
cannot know if theฺv uk button
mouse t h is
is pressed or not in this event handler.
i l an from
 Get the 2d context u secanvas object.
the
 Get n
m to
the(canvas bounds.
sa the X coordinate by using: event.clientX - canvasBounds.left;.
ukCalculate
V
an Calculate the Y coordinate by using: event.clientY - canvasBounds.top;.
Mil  To get better results, set fillStyle of the ctx object to a translucent color by setting it
to: "rgba(0,0,0,0.3)".
 Draw a small circle in the x, y coordinates with a radius of 3, filling it with the preceding
color.
Use the following code for reference:
function mouseMove(event) {
if (isdown) {
var ctx = canvas.getContext("2d");
var canvasBounds = canvas.getBoundingClientRect();
var x = event.clientX - canvasBounds.left;
var y = event.clientY - canvasBounds.top;
ctx.fillStyle = "rgba(0, 0, 0, 0.3)";
ctx.beginPath();
ctx.arc(x, y, 3, 0, 2 * Math.PI);
ctx.fill();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 13
}
}
8. Run the application and click in the canvas to paint with your mouse. Note that moving the
mouse while keeping the button pressed will create a continuous stroke.

You can check the solved version of the code.js and index.html files in the following folder:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

/home/oracle/labs/solutions/lab_08_04

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

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

Practices for Lesson 8: Advanced JavaScript


Chapter 8 - Page 14
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
o n -tr
Practices aforn Lesson 9: AJAX
s
a deฺ
and WebSocket
h
)
ฺrs 9t Gui
s
Chapter
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 1
Practices for Lesson 9: Overview
Practices Overview
In the practices for this lesson, you create two applications that use dynamic data and interact
with other clients by using AJAX and WebSocket.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

These practices must be developed in the lab environment to access the REST and WebSocket
services.

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

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 2
Practice 9-1: AJAX and REST
Overview
In this practice, you modify an existing project to add AJAX calls to get dynamic data from the
server.
The application that you create is a restaurant review site that allows users to add and remove
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

reviews.
The flow of the application is as follows:
• The application loads an empty page with a container where the content is rendered.
• It makes an AJAX call to the server to get the list of restaurants.
• It displays the list of restaurants to the user.
• The user clicks one of them, triggering another AJAX call to get the details of the
restaurant.
n s e
i ce
el
• The restaurant and its reviews are displayed.
• The user can go back or add and remove reviews. Each action triggers an AJAX call. a b l
fer
a n s
The following diagram shows the flow of the application:
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

You begin this practice with an existing project that contains all the necessary files.
• index.html: The HTML file that is used to run the application
• code.js: The JavaScript file that you will modify

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 3
The code.js file contains the following functions that are already implemented:
• window.addEventListener("load", function()): This event handler sets the
content variable to be the content element on the HTML page, and invokes the
loadList function when the page loads.
• showRestaurants(restaurants): This function creates the DOM elements to
display a list of restaurants. Each element has an anchor with a click event that triggers
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

the loadRestaurant function.


• showRestaurant(restaurant): This function creates the DOM elements to display
details of a restaurant object and all the reviews for the given restaurant. Each review
has a remove button that calls the removeReview function. Additionally, this function
creates fields to add a new review and a button that calls the addReview function when
it is clicked.
• createOption(value, label): This function creates an <option> element. It is e
n s
used in the showRestaurant method to add options to the <select> element.
i ce
• clearContent(): This function removes all the elements from the content element on
b l el
the page, allowing the other functions to add its contents to the page.
fer a
You need to implement the following functions to make the application work:
a n s
• n -tr
loadList(): You use AJAX to get the list of restaurants to be displayed, and then call
o
the showRestaurants function.
s an
• loadRestaurant(restaurant): You use AJAX
) h i eฺdetails of the selected
a to getdthe
restaurant, and then call the showRestaurant
s ฺrs t Gu
function.
• addReview(restaurant, text,
@ emrating):
u d enYoufunction.
use AJAX to add a review to the
restaurant, and then you callnthe
a t
loadRestaurant
S
• removeReview(restaurant, s s
k thireview): You use AJAX to remove a review from the
restaurant, andn ฺ vucall seloadRestaurant function.
i l a o uthe
then

n (m t
After you
ks a
have finished, your application should look similar to the following:
u
anV
Mil

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 4
Tasks
1. Open NetBeans 8.
2. Select File > Open Project from the menu.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

3. Browse to /home/oracle/labs/activities and open the lab_09_01 HTML 5 e


project. n s
i ce
b l el
fer a
a n s
n - tr
o
s an
) h a deฺ
s ฺrs t Gui
4. Open the index.html file.
@ em uden
a n S t
s
uk e thi s
ฺ v
m i lan to us
n (
ks a
V u
an
Mil
5. Review the file contents and familiarize yourself with the HTML elements.
6. Right-click the lab_09_01 project and select Run from the menu.

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

Practices for Lesson 9: AJAX and WebSocket


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

A browser window opens with a blank page. You modify the project to display application n s e
i ce
contents by using AJAX calls to get data from the server.
If you make changes to the project or close the web browser, you can use the run b l el
command to open it again with the new changes. fer a
a n s
7. Open the code.js file.
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
8. Review the existing methods. Refer s
uk e thi practice summary for an explanation on what
to the
they do. ฺ v
i lan tmethod.
9. Locate the loadList
m o us You must implement an AJAX call to get the list of
n ( and invoke the showRestaurants function with the list.
restaurants
s a
 kCreate a new XMLHttpRequest object.
u
V
an  Open the http://localhost:8080/JSConsole/rest/restaurants/ resource
Mil with a GET HTTP method.
 Add a callback function to the onload event of the XMLHttpRequest object.
 In the callback:
− Check whether readyState of the XMLHttpRequest object is equal to 4 and the
status is equal to 200
− If the previous check is true, parse the XMLHttpRequest responseText
property by using JSON.parse and get the list of restaurants
− Invoke the showRestaurants function with the parsed restaurants
 After the callback:
− Invoke the send method in the XMLHttpRequest object

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 6
Use the following code for reference:
function loadList() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",
"http://localhost:8080/JSConsole/rest/restaurants", true);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

xmlhttp.onload = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var restaurants = JSON.parse(xmlhttp.responseText);
showRestaurants(restaurants);
}
};
xmlhttp.send();
}
n s e
i ce
10.
11.
Run the application again. A list of restaurants is displayed in the browser window.
Note that clicking any of the restaurants does not do anything. b l el
fer a
12. Open the debug tools in the browser and click the Network tab.
a n s
13. Refresh the page.
o n -tr
an
14. Locate the AJAX call among the other network calls.
15. s
Explore the contents of the response. Note the JSON response.
h a deฺ
16. )
s Gui
Go to NetBeans and open the code.js file if it is not already open.
ฺ r
17. Locate the loadRestaurant function.m s
You must n t
implement an AJAX call to get the details
e
@ Stu
of a restaurant and invoke the showRestaurant d e function with the obtained response.
a n
s hiobject.
 Create a new XMLHttpRequest
u k t s
ฺ v
 Open a new GET
i l an o use
request to

( m
"http://localhost:8080/JSConsole/rest/restaurants/"
t +

 kAdd
ana callback function to the onload event of the XMLHttpRequest object.
restaurant.id.
s
V u
an  In the callback:
Mil − Check whether readyState of the XMLHttpRequest object is equal to 4 and the
status is equal to 200
− If the previous check is true, parse the XMLHttpRequest responseText
property by using JSON.parse and get the details of the restaurant
− Invoke the showRestaurant function with the parsed restaurant
 After the callback:
− Invoke the send method in the XMLHttpRequest object

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 7
Use the following code for reference:
function loadRestaurant(restaurant) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",
"http://localhost:8080/JSConsole/rest/restaurants/" +
restaurant.id, true);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

xmlhttp.onload = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var restaurant = JSON.parse(xmlhttp.responseText);
showRestaurant(restaurant);
}
};
xmlhttp.send();
n s e
i ce
el
}
18. Run the application again. A list of restaurants is displayed in the browser window.
a b l
19. Click a restaurant to see the details, reviews, and add review fields. fer
a n s
20.
21.
Open the debug tools in the browser and click the Network tab.
Refresh the page and click a restaurant again. o n -tr
22. Locate the AJAX call among the other network calls. s an
) h a deฺ
ฺrs t Gui
23. Explore the contents of the response. Note the JSON response.
24. s
Go to NetBeans and open the code.js file if it is not already open.
m den an AJAX call to send the form data
25. Locate the addReview function. @ Youemust implement
to the server to add a review.a n
Then, you S tuthe loadRestaurant function to refresh the
call
current restaurant. vuk
s his
n ฺ e t
 Create a new i la to u
empty s
review object by using the inline syntax:
n ( m
var review = {
a
ks 'text': text,
V u
an
'rating': rating

Mil };
 Create a new XMLHttpRequest object.
 Open a new POST request to
"http://localhost:8080/JSConsole/rest/restaurants/" +
restaurant.id.
 Add a callback function to the onload event of the XMLHttpRequest object.
 In the callback:
− Check whether readyState of the XMLHttpRequest object is equal to 4 and the
status is equal to 204
− If the previous check is true, invoke the loadRestaurant(restaurant)
function
 After the callback:
− Invoke the send method in the XMLHttpRequest object with
JSON.stringify(review) as the parameter.

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 8
Use the following code for reference:
function addReview(restaurant, text, rating) {
var review = {
'text': text,
'rating': rating
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

};
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST",
"http://localhost:8080/JSConsole/rest/restaurants/" +
restaurant.id, true);
xmlhttp.onload = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 204) {
loadRestaurant(restaurant);
n s e
i ce
el
}
};
a b l
xmlhttp.setRequestHeader("content-type", "application/json"); fer
a n s
}
xmlhttp.send(JSON.stringify(review));
o n -tr
26. Locate the removeReview function. You must implement s aannAJAX call to send a DELETE
h a deฺ function to refresh the
request to remove a review. Then you call the loadRestaurant
)
current restaurant.
s ฺrs t Gui
 Create a new XMLHttpRequest object.
@ em uden
 Open a new DELETE request
s a nto St
u k this
"http://localhost:8080/JSConsole/rest/restaurants/"
v +
ฺ e
m i lanfunction
restaurant.id+"/"+review.id.
t o u s
n (
 Add a callback to the onload event of the XMLHttpRequest object.

u ks−atheCheck
 In callback:

anV whether readyState of the XMLHttpRequest object is equal to 4 and the

Mil
status is equal to 204
− If the previous check is true, invoke the loadRestaurant(restaurant)
function
 After the callback:
− Invoke the send method in the XMLHttpRequest object

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 9
Use the following code for reference:
function removeReview(restaurant, review) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("DELETE",
"http://localhost:8080/JSConsole/rest/restaurants/" +
restaurant.id + "/" + review.id, true);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

xmlhttp.onload = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 204) {
loadRestaurant(restaurant);
}
};
xmlhttp.send();
}
n s e
27. Run the application. All functionality is available. i ce
b l el
You can check the solved version of the code.js file in the following folder: fer a
/home/oracle/labs/solutions/lab_09_01 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

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 10
Practice 9-2: WebSocket
Overview
In this practice, you create an interface for a multiplayer Tic-Tac-Toe game by using
WebSocket.
The game’s logic and player control is managed in the server.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

When you are connected to the server by using WebSocket, the server sends messages
notifying each player’s moves. Your application reads these messages and displays the game
interface. When a player makes a move, you send a message to the server by using the
existing WebSocket connection.
You create the interface for the game by using HTML and JavaScript. The interface is
composed of a 3x3 table with buttons or labels. The buttons represent the available slots that
can be played; the labels represent the played moves, for instance, after a player plays in a slot,
a label replaces the button.
n s e
i ce
el
When it is your turn, the buttons are enabled and display your icon (an X or an O) and your
opponent’s buttons are disabled, with nothing displayed.
a b l
fer
a n s
o n -tr
s an
) h a deฺ
s ฺrs t Gui
@ em uden
a n S t
s
uk e thi s
ฺ v
an that
ilgame o u s
m
The board of a(new
n t displayed in the X player’s window when it is X’s turn
is

u ksa
V
an
Mil

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 11
The board of a new game that is displayed in the O player’s window when it is X’s turn
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

An advanced board of the game that is displayed in the X player’s window when it is O’s turn

An advanced board of the game that is displayed in the O player’s window when it is O’s turn
n s e
i ce
Players connect to the server by using WebSocket to play each other. This allows players to b l el
play from different machines from anywhere as long as both connect to the same server. The fer a
server handles connections, game rules, and turns; when a player connects to the server, the
a n s
-
server sends a message notifying the player if the player will play with X or with O.
n tr
o
an
At this point, players send messages to the server notifying of the move taken. The message is
s
) h a deฺ
a JSON object with the coordinates and the player icon. The server responds by sending a

ฺrs t Gui
message to all the players, which contains a JSON object with the board status and the player
who has the next turn. s
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 12
WebSocket Messages
Server to Client Messages

Initial Message
The message is sent when a player connects, and is composed of a JSON object with two
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

properties:
• action: Is always “start.” It is used to identify the message.
• player: Can be either “CIRCLE” or “EXXES”
{"action":"start", "player":"CIRCLE"} or {"action":"start",
"player":"EXXES"}

Board Update Message


These are messages that are sent when turns happen. n s e
i ce
This message contains a JSON object with the following properties:
b l el
• board: A bi-dimensional 3x3 array of strings. Each string represents the state of each
fer a
slot. “NONE” means that the slot is empty; “EXXES” mean that an X is played in the
a n s
• o -tr
slot; “CIRCLE” means that a circle is played in the slot.
n
message: An informative message. It usually displays the current turn. If the game is
an
over, it contains details about who won the game.
s
• h a deฺ
currentTurn: Either “CIRCLE” or “EXXES,” representing whose turn it is next
)
s ฺrs t Gui
Empty Board:
@ em uden
a n S t
{"board":[["NONE","NONE","NONE"],["NONE","NONE","NONE"],["NONE","NONE"
,"NONE"]],"message":"EXXES s
uk e thi s
turn.","currentTurn":"EXXES"}
ฺ v
i an o us
lBoard:
( m
Game in Progress
n t
ks a
u
anV
Mil
{"board":[["EXXES","NONE","NONE"],["NONE","NONE","EXXES"],["CIRCLE","C
IRCLE","NONE"]],"message":"EXXES turn.","currentTurn":"EXXES"}

Client to Server Messages


Each player sends a message when it is their turn. The message is a JSON object with the
following properties:
• x: The X coordinate of the player’s move
• y: The Y coordinate of the player’s move
• player: Either “CIRCLE” or “EXXES,” representing the player that played the move
{"x":2,"y":1,"player":"CIRCLE"}

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 13
Tasks
1. Open NetBeans 8.
2. Select File > New Project from the menu.
3. Select the HTML5 category and the HTML 5 Application project. Click Next.
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
4. Name the project lab_09_02
u s
k thi and s
check that the project location is
ฺ v
n use
/home/oracle/labs/activities. Click Finish.
i l a
5. m
Modify the(index.html
n to file:
a the title of the page to Tic Tac Toe with WebSocket.
uks
 Change

n V Add a script reference to code.js in the <head> section of the file.


a
Mil  Inside the body, add a header and a div element with a “board” Id.
 Add another div element with a “currentMessage” Id. This element is used to display
the WebSocket messages.

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 14
Use the following code for reference:
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe with WebSockets</title>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<script src="code.js" type="text/javascript"></script>
</head>
<body>
<h1>Tic Tac Toe With Web Sockets</h1>
<div id="board"></div>
n s e
i ce
el
<div id="currentMessage"></div>
</body>
a b l
fer
</html>
a n s
6.
-tr
Right-click the Site Root node on the Projects tab and select New > JavaScript File.
o n
an
7. Set the name to code and click Finish.
8. Open the code.js file if it is not already open.
h s
a deฺ
9. Create four global variables.
ฺ r )
s Gui
 A player variable to store the tokenm s nt will use
that the player
 A currentMessage variable @ e u d e
to store atreference to the currentMessage div element
a n S
ฺ v uks aereference
 A board variable to store
t his to the board div element
i l an aoreference
 A socket to store
u s to the WebSocket connection
(mwindow tload event listener function.
10. Create a new
n
u k sathe player variable to an empty string.
 Set

an V  Set the currentMessage variable to the document element “currentMessage.”


Mil  Set the board variable to the document element “board.”
 Set the socket variable to a new WebSocket object that connects to:
"ws://localhost:8080/JSConsole/ws/gameWebSocket"
 Set the onmessage handler to a function called onWebSocketMessage. You create
this function in the next step.

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 15
Use the following code for reference:
window.addEventListener("load", function() {
player = "";
currentMessage = document.getElementById("currentMessage");
board = document.getElementById("board");
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

socket = new
WebSocket("ws://localhost:8080/JSConsole/ws/gameWebSocket");
socket.onmessage = onWebSocketMessage;
});
11. Create the onWebSocketMessage(event) function.
The following steps are part of the onWebSocketMessage function.
12. Create a new data variable and set it to JSON.parse(event.data).
13. Set innerHTML of currentMessage to event.data to display the WebSocket n s e
i ce
messages as they arrive.
b l el
var data = JSON.parse(event.data);
fer a
currentMessage.innerHTML = event.data;
a n s
WebSocket messages. o n -tr
14. Refer to the overview for details on the contents of the data object that is sent in the

s an
15. If data.action is equal to "start", set the player variable to data.player. The
) h a deฺ
ฺrs t Gui
function should end here if the condition is true.
if (data.action === "start") { s
player = data.player;
@ em uden
a n S t
return; s
uk e thi s
} ฺ v
16. If data.action
m i laisnnotto"start,"
us it means that the board is being sent and a turn is to be
taken. You
n ( must use the board data inside the message to display the board. If it is your
turn, a
ksbuttons
you display the board with the buttons; if it is not your turn, you display the board with
u
nV
the disabled.
a
Mil
17. Start by creating a table element.
var table = document.createElement("table");
18. Create an icon variable and assign it to: player === "EXXES" ? "X" : "O" to have
quick access to the player icon.
var icon = player === "EXXES" ? "X" : "O";
19. Iterate the rows.
for (y = 0; y < 3; y++) {
20. Create a table row (tr) element.
var row = document.createElement("tr");
21. Iterate the columns.
for (x = 0; x < 3; x++) {

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 16
22. Create a cell element (td).
var cell = document.createElement("td");
23. Get the value for the element on the current position of data.board.
var value = data.board[x][y];
24. If the value is equal to "NONE", then:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

if (value === "NONE") {


25. Create a button by creating an input element and set its type attribute to "button".
var button = document.createElement("input");
button.setAttribute("type", "button");
26. If the player variable is equal to data.currentTurn
if (player === data.currentTurn) {
27. Set the value attribute to the icon variable to display the player icon in each button.
n s e
button.setAttribute("value", icon);
i ce
28. Add a click listener to the button that calls the send function to send a message by using
b l el
WebSocket.
fer a
 Create an anonymous function to copy the current values of X and Y.
a n s
 Inside the function, add the event listener.
o n -tr
 Invoke the send function by using the copied values.
s an
(function(xcopy, ycopy) {
) h a deฺ
ฺrs t Gui
button.addEventListener("click", function() {
s
send(xcopy, ycopy);
@ em uden
});
a n S t
})(x, y); s
uk e thi s
ฺ v
an oforuthe
29. Add an else statement
i l s player===data.currentTurn condition.
(
}else{
n m t
a
30. Setsthe button value attribute to " " and the disabled attribute to "disabled" and close
V uthek else statement.
an
Mil button.setAttribute("value", " ");
button.setAttribute("disabled", "disabled");
}
31. Append the button to the cell and close the “if value==="none"” condition.
cell.appendChild(button);
}
32. If the value is equal to "EXXES", append an "X" text element to the cell.
if (value === "EXXES") {
cell.appendChild(document.createTextNode("X"));
}

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 17
33. If the value is equal to "CIRCLE", append an "O" text element to the cell.
if (value === "CIRCLE") {
cell.appendChild(document.createTextNode("O"));
}
34. Append the cell to the row and close the column iteration.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

row.appendChild(cell);
}
35. Append the row to the table and close the row iteration.
table.appendChild(row);
}
36. Remove all elements from the board element by using the following code:
while (board.firstChild) {
n s e
ce
board.removeChild(board.firstChild);
}
eli
a b l
37. Finally append the table to the board and close the function.
fer
board.appendChild(table);
a n s
}
o n -tr
With this, the onWebSocketMessage function is completed.n
a
38. Create a new send function that receives the X and a Ys eฺ
coordinates.
) h
s with i d
39. Inside the function, create a new anonymousฺrobject
s G uthe x, y, and player attributes.
40. Use socket.send with the stringified em en t
JSON representation of the previous object.
n @
41. Use the following code for reference: t u d
s a s S
function send(x,
ฺ v uk y)e{ thi
messagea=
m i l n {x:
t o
x,s y: y, player: player};
u
n (
socket.send(JSON.stringify(message));
a
ksthe application and open the page in two browsers to play.
}
u
anV
42. Run

Mil You can check the solved version of the code.js and index.html files in the following folder:
/home/oracle/labs/solutions/lab_09_02

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

Practices for Lesson 9: AJAX and WebSocket


Chapter 9 - Page 18
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
o n -tr
n
AppendixaJSConsole
Examplesh s
a deฺ
)
ฺrs 10t Gui
s
Chapter
@ em uden
a n S t
s
uk e thi s
ฺ v
an s
n (mil to u
u ksa
n V
a
Mil

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

Appendix JSConsole Examples


Chapter 10 - Page 1
Lesson 3 JavaScript Fundamentals
Variables and Types
Examples for Variables and Types
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

/lesson03/variables_and_types/code.js
// Declaring a Variable
function declareVariable() {
if (true) {
var x = "Declared in a block of code";
}
console.log("Value of x: " + x);
}

declareVariable();
n s e
i ce
b l el
Expressions and Operators
fer a
Examples for Expressions and Operators
a n s
o n -tr
/lesson03/expressions_and_operators/code.js
s an
console.log("**Creating and Array and an Object**");
) h a deฺ
ui
// Creating and Array and an Object
var courses = ["Java", "JavaScript", "Web
s ฺ r sServices"];
G
var students = [12, 5, 7];
e m dent
console.log("courses array a =>n"@ S tu
+ courses);

ฺ v uks e=> t"hi+sstudents);


console.log("students array

i
var course = {name:
m lan"JavaScript",
t o u s students: 5, frequency: "daily"};
(
s an
console.log("course
k
object => " + course);

V ustudents_new = new Array();


an var

Mil var students_new_init = new Array(12, 5, 7);

console.log("students_new array => " + students_new);


console.log("students_new_init array => " + students_new_init);

function Courses() {
}

var courses_new = new Courses();


var courses_new_init = new Courses(12, 5, 7);

console.log("courses_new object => " + courses_new);


console.log("courses_new_init object => " + courses_new_init);

console.log("**Accessing an Array and an Object**");


// Accessing an Array and an Object
var myObject = {
name: "Ring",
diameter: 12,
specs: {

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

Appendix JSConsole Examples


Chapter 10 - Page 2
material: "Wood",
waterProof: false
}
};
var myArray = ["one", "two", 3, "four", 5];
console.log("myObject.diameter => " + myObject.diameter);
console.log("myObject.specs.waterProof => " + myObject.specs.waterProof);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

console.log("myObject['diameter'] => " + myObject["diameter"]);


console.log("myObject['specs]['material'] => " +
myObject["specs"]["material"]);
console.log("myArray[0] => " + myArray[0]);
console.log("myArray[5] => " + myArray[5]);

console.log("**Creating and Calling a Function**");


// Creating and Calling a Function
function multiply(x, y) {
var result = x * y;
n s e
return result;
i ce
}
b l el
fer a
var total = multiply(135, 6);
a n s
tr
console.log("total: " + total);

o n -
an
console.log("**Operators**");
// Operators
console.log("9 - 5 => " + (9 - 5)); h s
a deฺ
)
rs t Gui
console.log("'9' + 5 => " + "9" + 5); sฺ
console.log("[9] * ['5'] => " + [9] * ['5']);
m den
console.log("9 == '9' => " + (9 ==e'9'));
@ tu+ "string" && "another");
console.log("9 === '9' => " +n(9 === '9'));
a S
s his
console.log("'string' &&k'another'
u 'another' => "
console.log("'string'
n ฺ v||
e t => " + "string" || "another");
la u s
x i = 100;to
console.log("!'string' => " + !"string");
var a, b = 5,m
(
k s an =+=b1=>=>""++(a(x=+=b));
console.log("a

V u
console.log("x
console.log("5 & 6 => " + (5 & 6));
1));

anvar age = 18;


Mil var status = (age >= 18) ? "major" : "minor";
console.log("status => " + status);

console.log("**Special Operators**");
// Special Operators
for (var i = 0, j = 9; i <= 9; i++, j--)
console.log(i + " , " + j);

var i = {a: 5, s: "String", b: 15};


delete i.s;
console.log("'b' in i => " + ("b" in i));
console.log("'s' in i => " + ("s" in i));

var i = [5, "String", 15];


delete i[1];
console.log("0 in i => " + (0 in i));
console.log("1 in i => " + (1 in i));

var a = [1, 2, 3, 4];


console.log("typeof undefined => " + typeof undefined);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 3
console.log("typeof 'Hello' => " + typeof "Hello");
console.log("typeof a => " + typeof a);
console.log("typeof a[0] => " + typeof a[0]);

/lesson03/expressions_and_operators/index.html
<!DOCTYPE html>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Expressions and Operators section</title>
<meta charset="UTF-8">
<script src="code.js"></script>
</head>
<body>
JavaScript code only. Open console<br>
<a href="javascript:void(0);">This link does nothing</a>
n s e
</body>
i ce
</html>
b l el
Statements and Loops fer a
a n s
Examples for Statements and Loops
n - tr
o
/lesson03/statements_and_loops/code.js
s an
console.log("**Statements**");
) h a deฺ
ฺrs t Gui
// Statements
for (var i = 0; i < 10; i++) { s
if (i === 5)
@ em uden
continue;
console.log("This numbersa
n S t
uk e thi s
is:" + i);
}
ฺ v
m i lan to us
n (
console.log("**while loop**");
s a
uik= 0;
// while loop
V
var
nwhile (i < 10) {
a
Mil }
console.log(i += 1);

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

console.log("**for loop**");
// for loop
for (var i = 1; i <= 10; i += 1) {
console.log(i);
}

var myObject = {
one: "value of property one",
two: "value of property two"
};

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

Appendix JSConsole Examples


Chapter 10 - Page 4
for (var myVar in myObject) {
if (myObject.hasOwnProperty(myVar)) {
console.log(myVar);
}
}

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

Examples for Objects

/lesson03/objects/code.js
console.log("**Creating Objects**");
// Creating Objects
var obj_1 = {};
var obj_2 = new Object();
var obj_3 = Object.create(null);
n s e
i ce
el
console.log("obj_1 => " + obj_1.toSource());
console.log("obj_2 => " + obj_2.toSource());
a b l
//console.log("obj_3 => " + obj_3); // obj_3 doesn't inherit anything
fer
a n s
var person = {
"full-name": "John Doe", n - tr
o
age: 35,
s an
address: {
) h a deฺ
ฺrs t Gui
address_line1: "Clear Trace, Glaslyn, Arkansas",
"postal code": "76588-89"
s
em uden
}
};
@
an is St
console.log("person => "k+sperson.toSource());
n ฺ vu se th
( m ila height,
// Creating an object
function Tree(type, t o u new
with
age) {
n
ksa = height;
this.type = type;
u
this.height

an Vthis.age = age;
Mil
}

var mapleTree = new Tree("Big Leaf Maple", 80, 50);

console.log("mapleTree => " + mapleTree.toSource());

//Creating an object with prototypes


var myChild = Object.create(Object.prototype); // Object {}
console.log("myChild => " + myChild.toSource());
myChild = Object.create({a: 10, b: 30}); // Object {a=10, b=30}
console.log("myChild => " + myChild);

var myObj = {
a: 10,
b: 30
};
myChild = Object.create(myObj);
console.log("myChild => " + myChild);
console.log("myChild.a => " + myChild.a); //10
console.log("myChild.b => " + myChild.b); //30

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

Appendix JSConsole Examples


Chapter 10 - Page 5
console.log("**Accessing Objects**");
// Creating Objects
var myObject = {
name: "luggage",
length: 75,
specs: {
material: "leather",
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

waterProof: true
}
};

console.log("myObject['name'] => " + myObject["name"]); //"luggage"


console.log("myObject.name => " + myObject.name); //"luggage"
console.log("myObject.specs.material => " + myObject.specs.material);
//"leather"
console.log("myObject['specs']['material'] => " +
myObject["specs"]["material"]); //"leather"
n s e
console.log("myObject.width => " + myObject.width); //undefined
i ce
// console.log("myObject.tags.number => " + myObject.tags.number); //
b l el
TypeError thrown
fer a
// line commented to allow following commands to run
a n s
tr
myObject["name"] = "suitcase"; // name : "suitcase"
n -
console.log("myObject['name'] => " + myObject["name"]); //"suitcase"
o
an
myObject.name = "suitcase"; // name : "suitcase"

myObject.width = 40; h s
console.log("myObject.name => " + myObject.name); //"suitcase"
a deฺ
// creates a new property
)
ฺrs t Gui
console.log("myObject.width => " + myObject.width); // 40
s
em uden
//myObject.tags.number = 6; // TypeError thrown
// line commented to allow following commands to run
a n @ S t
console.log("**Working with Object Properties**");
s
uk e thi
// Working with Object Properties s
ฺ v
console.log(delete myObject.length);
an s
mil to u
console.log(delete myObject.height);

n (
ksa
var myObject = {

V uone: "property value one",


two: "property value two"
an
Mil
};

for (var myVar in myObject) {


if (myObject.hasOwnProperty(myVar)) {
console.log(myVar);
}
}

console.log("**Accessing Object Properties**");


// Accessing Object Properties
var obj = {
a: 45,
get double_a() {
return this.a * 2;
},
set modify_a(x) {
this.a -= x;
}
};

console.log("obj.a => " + obj.a); // 45


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

Appendix JSConsole Examples


Chapter 10 - Page 6
console.log("obj.double_a => " + obj.double_a); // 90
obj.modify_a = 40;
console.log("obj.a => " + obj.a); // 5
console.log("obj.double_a => " + obj.double_a); //10

console.log("**Object Methods**");
// Object Methods
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

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

Arrays e
n s
Examples for Arrays
i ce
b l el
/lesson03/arrays/code.js
fer a
console.log("**Creating Arrays**");
a n s
-tr
// Creating Arrays
var myNewEmptyArray = [];
o n
an
console.log("myNewEmptyArray => " + myNewEmptyArray);
s
) h a deฺ
ฺrs t Gui
var numbers = [1, 2, 3, 4, 'five'];
console.log("numbers => " + numbers);
s
// Creating array with new
@ em uden
a n
var myNewEmptyArray = new Array();
S t
s
uk e thi
console.log("myNewEmptyArray => " s
+ myNewEmptyArray);
ฺ v
i lan to= unews Array(15);
var myNewNonEmptyArray
m
n (
console.log("myNewNonEmptyArray => " + myNewNonEmptyArray);

u ksa = new Array(1, 2, 3, 4, 'five');


var numbers
V
nconsole.log("numbers => " + numbers);
a
Mil console.log("**Accessing Array Elements**");
// Accessing Array Elements
var c = ["blue", "red", "green", "purple"];
console.log("c.length => " + c.length);
c[20] = "white";
console.log("c.length => " + c.length);

// iterating arrays
// prints all the elements in the array, including undefined
for (var i = 0; i < c.length; i += 1) {
console.log(c[i]);
}

// prints the elements not undefined in the array


for (var i in c) {
console.log(c[i]);
}

console.log("**Multi-dimensional Arrays**");
// Multi-dimensional Arrays
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 7
var myArr = new Array(10);
for (i = 0; i < 10; i++) {
myArr[i] = new Array(10);
for (j = 0; j < 10; j++) {
myArr[i][j] = "[" + i + j + "]";
}
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

console.log("myArr => " + myArr);

var tic_tac_toe = [
[0, 0, 'X'],
['X', 0, 'X'],
['X', 0, 0]
];

console.log("tic_tac_toe => " + tic_tac_toe);


n s e
i ce
Functions b l el
Examples for Functions fer a
a n s
/lesson03/functions/code.js n - tr
o
console.log("**Defining Functions**");
s an
// Defining Functions
) h a deฺ
ฺrs t Gui
function multiply(x, y) {
var result = x * y;
s
em uden
return result;
}
a n @ S t
s
k thi s
"u+ total);
var total = multiply(135, 6);
ฺ v
an o use
console.log("total =>
i l
(m t Functions**");
console.log("**Anonymous
n
ksa = function(x, y) {
// Anonymous Functions
u
var multiply

an Vvar result = x * y;
Mil
return result;
};

console.log("multiply(135, 6) => " + multiply(135, 6));

console.log("**Calling a Function**");
// Calling a Function
console.log("*function as a method*");
// function as a method
var myObj = {
name: "Hello World!",
print: function(message) {
console.log(this.name + message);
}
};

myObj.print(' JS Robot');

console.log("*function as a constructor*");
// function as a constructor
function Tree(type, height) {
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 8
this.type = type;
this.height = height;
}

Tree.prototype.getType = function() {
return this.type;
};
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var myTree = new Tree("Big Leaf Maple", 80);

console.log("myTree.getType() => " + myTree.getType()); // "Big Leaf Maple"

console.log("**The arguments variable**");


// The arguments variable
function sum() {
var total = 0;
for (var i = 0, l = arguments.length; i < l; i++) {
n s e
total += arguments[i];
i ce
}
b l el
return total;
fer a
}
a n s
n
console.log("sum(1,2,3,4,5) => " + sum(1, 2, 3, 4, 5)); //15
o -tr
console.log("**Recursion**");
s an
// Recursion
) h a deฺ
function factorial(number) {
s ฺrs t Gui
em uden
if (number < 2)
return 1;
a
return number * factorial(number @
n -S1); t
} s
uk e thi s
ฺ v
i la< n2) t?onumber
function fibonacci(number)
m us{ : fibonacci(number - 1) + fibonacci(number
(
return (number
n
- 2);
ks a
}
V u
anconsole.log("factorial(10)
Mil
=> " + factorial(10));
console.log("fibonacci(10) => " + fibonacci(10));

console.log("**Scopes**");
// Scopes
console.log("*global scope*");
var x = "I am a global var!";
function printVar()
{
console.log(x);
}

printVar();
console.log("window.x => " + window.x);

// function scope
console.log("*function scope*");
function declareVariable() {
if (true) {
var x = "Declared in a block of code";
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 9
console.log("Value of x: " + x);
}

declareVariable();
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

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

Appendix JSConsole Examples


Chapter 10 - Page 10
Lesson 4 Combining HTML5 and JavaScript in Web Applications
HTML5 Sections
Divide the document by sections.

/lesson04/html5_sections/index.html
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>
</head>
<body>
n s e
ce
<header>
<h1>The Next Big Conference for Front-End Developers</h1>
eli
<h2>Join us this year</h2>
a b l
<nav>
fer
<ul>
a n s
<li><a href="#">Home</a></li>
n - tr
<li><a href="#section-1">Speakers</a></li>
o
an
<li><a href="#section-2">Workshops</a></li>
s
) h a deฺ
<li><a href="#section-3">Submit Proposal</a></li>

ฺrs t Gui
</ul>
</nav>
s
</header>
@ em uden
<section id="section-1">
a n S t
<article>
s
uk e thi s
<header>
ฺ v
an
<h1>Speakers</h1>
s
n (mil to u
</header>
<p>Text</p>

u ksa<p>More Text</p>

n V <p>Even More Text</p>


a <p>Text</p>
Mil </article>
</section>
<section id="section-2">
<article>
<header>
<h1>Workshops</h1>
</header>
<p>Text</p>
<p>More Text</p>
<p>Even More Text</p>
<p>Text</p>
</article>
</section>
<section id="section-3">
<article>
<header>
<h1>Submit Proposal</h1>
</header>
<p>Text</p>
<p>More Text</p>

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

Appendix JSConsole Examples


Chapter 10 - Page 11
<p>Even More Text</p>
<p>Text</p>
</article>
</section>
<aside>
<h1>Ads</h1>
<p>UI/UX advertising</p>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

</aside>
<footer>
<p>&copy; 2014 Front End User Groups</p>
</footer>
</body>
</html>

HTML5 Forms
Create a form with HTML5 elements.
n s e
i ce
/lesson04/html5_forms/index.html
b l el
<!DOCTYPE html>
fer a
<html>
a n s
<head>
<title>The Next Big Front-End Conference</title> n - tr
o
<meta charset="UTF-8">
s an
<link rel="stylesheet" href="styles.css">
) h a deฺ
ฺrs t Gui
<script src="code.js"></script>
</head>
s
em uden
<body>
<header>
a n @ S t
<h1>The Next Big Conference for Front-End Developers</h1>
s
uk e thi
<h2>Join us this year</h2> s
ฺ v
an
<nav>
s
mil to u
<ul>

n (
<li><a href="#">Home</a></li>

ksa
<li><a href="#section-1">Speakers</a></li>

V u <li><a href="#section-2">Workshops</a></li>

an <li><a href="#section-3">Submit Proposal</a></li>

Mil
</ul>
</nav>
</header>c
<section id="section-1">
<article>
<header>
<h2>Speakers</h2>
</header>
<p>Text</p>
</article>
</section>
<section id="section-2">
<article>
<header>
<h2>Workshops</h2>
</header>
<p>Text</p>
</article>
</section>
<section id="section-3">
<article>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 12
<header>
<h2>Submit Proposal</h2>
</header>
<p>
Fill in the form below to send your proposal:
</p>
<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>
i ce
<input type="tel" name="telephone" id="telephone">
b l el
</p>
fer a
<p><label for="abstract">Abstract:(required)</label></p>
a n s
tr
<textarea rows="5" cols="80" name="abstract"
id="abstract"></textarea>
o n -
an
<p><label for="file">Or you can send us a document with the
abstract:</label></p>
h s
a deฺ
<input type="file" name="file" id="file">
)
ฺrs t Gui
<p><input type="submit" name="submit" value="submit"></p>
s
em uden
</fieldset>
</form>
</article>
a n @ S t
</section> s
uk e thi s
<aside> ฺ v
an s
mil to u
<h2>Ads</h2>
(
<p>UI/UX advertising</p>
n
ksa
</aside>

V u <footer>
<p>&copy; 2014 Front End User Groups</p>
an
Mil
</footer>
</body>
</html>

HTML5 Form Validation


Validate HTML5 form elements.

/lesson04/html5_form_validation/index.html
<!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>
</head>
<body>
<header>
<h1>The Next Big Conference for Front-End Developers</h1>
<h2>Join us this year</h2>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 13
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#section-1">Speakers</a></li>
<li><a href="#section-2">Workshops</a></li>
<li><a href="#section-3">Submit Proposal</a></li>
</ul>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

</nav>
</header>
<section id="section-1">
<article>
<header>
<h2>Speakers</h2>
</header>
<p>Text</p>
</article>
</section>
n s e
<section id="section-2">
i ce
<article>
b l el
<header>
fer a
<h2>Workshops</h2>
a n s
tr
</header>
<p>Text</p>
o n -
an
</article>
</section>
<section id="section-3"> h s
a deฺ
<article> )
ฺrs t Gui
s
em uden
<header>
<h2>Submit Proposal</h2>
</header>
a n @ S t
<p> s
uk e thi s
ฺ v
Fill in the form below to send your proposal:
an s
mil to u
</p>
(
<form action="#" name="proposalForm">
n
ksa
<fieldset>

V u <p>
<label for="name">Name:(required)</label>
an
Mil
<input type="text" name="name" id="name" required>
</p>
<p>
<label for="email">Email:(required)</label>
<input type="email" name="email" id="email" required>
</p>
<p>
<label for="telephone">Telephone:</label>
<input type="tel" name="telephone" id="telephone"
placeholder="(000) 000-0000"
pattern="\([2-9][0-9]{2}\) [0-9]{3}-[0-9]{4}">
</p>
<p><label for="abstract">Abstract:(required)</label></p>
<textarea rows="5" cols="80" name="abstract" id="abstract"
required></textarea>
<p><label for="file">Or you can send us a document with the
abstract:</label></p>
<input type="file" name="file" id="file">
<p><input type="submit" name="submit" value="submit"></p>
</fieldset>
</form>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 14
</article>
</section>
<aside>
<h2>Ads</h2>
<p>UI/UX advertising</p>
</aside>
<footer>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<p>&copy; 2014 Front End User Groups</p>


</footer>
</body>
</html>

HTML5 Form Submission


Submit a form with HTML5 elements.

/lesson04/html5_form_submission/index_form_submit.html
n s e
i ce
el
<!DOCTYPE html>
<html>
a b l
<head>
fer
<title>The Next Big Front-End Conference</title>
a n s
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css"> n - tr
o
<script src="code.js"></script>
s an
</head>
) h a deฺ
ฺrs t Gui
<body>
<header>
s
em uden
<h1>The Next Big Conference for Front-End Developers</h1>
<h2>Join us this year</h2>
<nav>
a n @ S t
<ul> s
uk e thi s
ฺ v
an
<li><a href="#">Home</a></li>
s
mil to u
<li><a href="#section-1">Speakers</a></li>

n (
<li><a href="#section-2">Workshops</a></li>

ksa
<li><a href="#section-3">Submit Proposal</a></li>

V u </ul>

an </nav>

Mil
</header>
<section id="section-1">
<article>
<header>
<h2>Speakers</h2>
</header>
<p>Text</p>
</article>
</section>
<section id="section-2">
<article>
<header>
<h2>Workshops</h2>
</header>
<p>Text</p>
</article>
</section>
<section id="section-3">
<article>
<header>
<h2>Submit Proposal</h2>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 15
</header>
<p>
Fill in the form below to send your proposal:
</p>
<form action="/JSConsole/FormSubmissionServlet" name="proposalForm"
method="post"
enctype="multipart/form-data">
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>
i ce
<input type="tel" name="telephone" id="telephone">
b l el
</p>
fer a
<p><label for="abstract">Abstract:(required)</label></p>
a n s
tr
<textarea rows="5" cols="80" name="abstract"
id="abstract"></textarea>
o n -
an
<p><label>Or you can send us a document with the
abstract:</label></p>
h s
a deฺ
<input type="file" name="file" multiple>
)
ฺrs t Gui
<p><input type="submit" name="submit" value="submit"></p>
s
em uden
</fieldset>
</form>
</article>
a n @ S t
</section> s
uk e thi s
<aside> ฺ v
an s
mil to u
<h2>Ads</h2>
(
<p>UI/UX advertising</p>
n
ksa
</aside>

V u <footer>
<p>&copy; 2014 Front End User Groups</p>
an
Mil
</footer>
</body>
</html>

/lesson04/html5_form_submission/FormSubmissionServlet.java
package lesson04.html5_form_submission;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Scanner;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

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

Appendix JSConsole Examples


Chapter 10 - Page 16
@WebServlet(name = "FormSubmissionServlet", urlPatterns =
{"/FormSubmissionServlet"})
@MultipartConfig
public class FormSubmissionServlet extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
n s e
response.setContentType("text/html;charset=UTF-8");
i ce
try (PrintWriter out = response.getWriter()) {
b l el
out.println("<!DOCTYPE html>");
fer a
out.println("<html>");
a n s
tr
out.println("<head>");
n -
out.println("<title>Servlet FormSubmissionServlet</title>");
o
an
out.println("</head>");
out.println("<body>");
h s
a deฺ
out.println("<h1>Parameters received: </h1>");
)
ฺrs t Gui
Enumeration e = request.getParameterNames();
s
em uden
while (e.hasMoreElements()) {
Object obj = e.nextElement();
a n @ S
String fieldName = (String) obj;t
s
uk e thi s
String fieldValue = request.getParameter(fieldName);
ฺ v
out.println(fieldName + " : " + fieldValue + "<br>");
an s
mil to u
}
(
Part filePart = request.getPart("file");
n
ksa
String fileText = getFileText(filePart);

V u out.println(filePart.getName() + " : " + fileText + "<br>");


// For multiple files selected
an
Mil
/*for (Part p : request.getParts()) {
out.println(p.getName() + " : " + p.getInputStream().toString() +
"<br>");
}*/
out.println("</body>");
out.println("</html>");
}
}

private static String getFileText(Part filePart) {


String uploadedText = "";
if (null != filePart) {
try {
InputStream fileContent = filePart.getInputStream();
uploadedText = new Scanner(fileContent).
useDelimiter("\\A").next();
} catch (IOException ex) {
}
}
return uploadedText;
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 17
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click
on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

* @param response servlet response


* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
processRequest(request, response);
}
n s e
i ce
/**
b l el
* Handles the HTTP <code>POST</code> method.
fer a
*
a n s
tr
* @param request servlet request
* @param response servlet response
o n -
an
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/ h s
a deฺ
@Override )
ฺrs t Gui
s
em uden
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
a n @ S t
throws ServletException, IOException {
s
uk e thi s
processRequest(request, response);
} ฺ v
an s
/**
n (mil to u
ksa
* Returns a short description of the servlet.

V u *
* @return a String containing servlet description
an
Mil
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

HTML5 Events
Handle HTML5 events.

/lesson04/html5_events/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>The Next Big Front-End Conference</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<script src="code.js"></script>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 18
</head>
<body>
<header>
<h1>The Next Big Conference for Front-End Developers</h1>
<h2>Join us this year</h2>
<nav>
<ul>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<li><a href="#">Home</a></li>
<li><a href="#section-1">Speakers</a></li>
<li><a href="#section-2">Workshops</a></li>
<li><a href="#section-3">Submit Proposal</a></li>
</ul>
</nav>
</header>
<section id="section-1" onclick="showSpeakersBanner()">
<article>
<header>
n s e
<h2>Speakers</h2>
i ce
</header>
b l el
<p>text</p>
fer a
</article>
a n s
tr
</section>
<section id="section-2">
o n -
an
<article>
<header>
<h2>Workshops</h2> h s
a deฺ
</header> )
ฺrs t Gui
s
em uden
<p>Text</p>
</article>
</section>
a n @ S t
s
uk e thi
<section id="section-3"> s
<article> ฺ v
an s
mil to u
<header id="headerProposal">

n (
<h2>Submit Proposal</h2>

ksa
</header>

V u <p>
Fill in the form below to send your proposal:
an
Mil
</p>
<form name="proposalForm">
<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>
<label for="telephone">Telephone:</label>
<input type="tel" name="telephone" id="telephone">
</p>
<p><label for="abstract">Abstract:(required)</label></p>
<textarea rows="5" cols="80" name="abstract"
id="abstract"></textarea>
<p><label for="file">Or you can send us a document with the
abstract:</label></p>
<input type="file" name="file" id="file">
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 19
<p><input type="submit" name="submit" value="submit"></p>
</fieldset>
</form>
</article>
</section>
<aside>
<h2>Ads</h2>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<p>UI/UX advertising</p>
</aside>
<footer>
<p>&copy; 2014 Front End User Groups</p>
</footer>
</body>
</html>

/lesson04/html5_events/code.js e
n s
window.addEventListener("load", function() {
i ce
alert("Window load event listener fired!");
}, false); b l el
fer a
window.addEventListener("load", function() {
a n s
o n -tr
document.getElementById("section-2").onclick = showWorkshopBanner;
document.getElementById("headerProposal").addEventListener("click",
showAbstractBanner, false);
s an
}, false);
) h a deฺ
function showSpeakersBanner()
s ฺ rs t Gui
{ m speakers
ebest d en in the region");
alert("This year we'll have the
a n @ S t u
}
s
uk e thi s
;
ฺ v
m i lan to us
function showWorkshopBanner()
{
n (
s a
} uk
alert("Our workshops are real hands-on!");
V
anfunction showAbstractBanner()
Mil {
alert("Don't miss the opportunity to present your next big idea!");
}

DOM Manipulation
Alter the structure of the document.

/lesson04/dom_manipulation/code.js
function replaceText() {
// create a paragraph element, the variable contains a reference to the p
element
var newParagraphElement = document.createElement("p");
var text = "This is the new Text";
// create a text node
var newTextElement = document.createTextNode(text);
// insert the newly created text node into the node tree of paragraph
newParagraphElement.appendChild(newTextElement);

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

Appendix JSConsole Examples


Chapter 10 - Page 20
var currentParagraphElement = document.getElementById("p-1");
// get parent node
var parentNode = currentParagraphElement.parentNode;
parentNode.replaceChild(newParagraphElement, currentParagraphElement);
}

function removeText() {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var currentParagraphElement = document.getElementById("p-2");


// get parent node
var parentNode = currentParagraphElement.parentNode;
parentNode.removeChild(currentParagraphElement);
}

function duplicateText() {
var currentParagraphElement = document.getElementById("p-3");
// clone node
var clonedNode = currentParagraphElement.cloneNode(true);
n s e
// get parent node
i ce
var parentNode = currentParagraphElement.parentNode;
b l el
// insert the newly created node into the node tree of paragraph
fer a
parentNode.appendChild(clonedNode);
a n s
tr
}

o n -
an
function insertTextBefore() {

// create a paragraph element, the variableha s


containseaฺ reference to the p
element
ฺ r s ) u id
var text = "This is the new Text"; e ms dent G
var newParagraphElement = document.createElement("p");

// create a text node


a n @ Stu
v ks this
var newTextElement = document.createTextNode(text);
ucreated
• // insert the newly
a n ฺ s etext node into the node tree of paragraph
m i l to u
newParagraphElement.appendChild(newTextElement);
n (
k s a
var currentParagraphElement = document.getElementById("p-3");
u
n Vvar parentNode = currentParagraphElement.parentNode;
// get parent node
a
Mil // insert the newly created node into the node tree of paragraph
parentNode.insertBefore(newParagraphElement, currentParagraphElement);
}

/lesson04/dom_manipulation/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Manipulating the DOM</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
<script src="code.js"></script>
</head>
<body>
<p id="p-1">This is the original text</p>
<button onclick="replaceText()">Replace Text</button>
<p>
<p id="p-2">This is the original text</p>

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

Appendix JSConsole Examples


Chapter 10 - Page 21
<button onclick="removeText()">Remove Text</button>
<p id="p-3">This is the original text</p>
<button onclick="duplicateText()">Duplicate Text</button>
<button onclick="insertTextBefore()">Insert Text Before</button>
</body>
</html>
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

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

Appendix JSConsole Examples


Chapter 10 - Page 22
Lesson 5 The JavaScript API
JavaScript Parsing Numbers
Parse and validate numbers.

/lesson05/numbers/code.js
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

window.addEventListener("load", function() {
var button = document.getElementById("ageButton");
button.addEventListener("click", function() {
var ageOutputElement = document.getElementById("ageOutput");
var ageTextElement = document.getElementById("ageInput");
var ageTextValue = ageTextElement.value;
var age = parseInt(ageTextValue, 10);
var result = "";
if (isNaN(age)) {
n s e
result = "Input a number please.";
i ce
ageTextElement.value = "";
b l el
} else {
result = ((100 - age) + " years before you turn 100!");
fer a
}
a n s
console.log(result);
o n -tr
an
ageOutputElement.innerHTML = result;
}, false);
}, false);
h s
a deฺ
)
ฺrs { t Gui
window.addEventListener("load", function() s
m den
efunction()
var button = document.getElementById("tipButton");
@
a n
button.addEventListener("click",
S tu {

uk=sdocument.getElementById("tipTotalBill");
is
var tipOutputElem = document.getElementById("tipOutput");

var tipTotalBillElem
v t h
l u
var tipNumberOfPeopleElem
i se = document.getElementById("tipNumberOfPeople");
a=nparseFloat(tipTotalBillElem.value);
var billTotal
n to
(m= parseFloat(tipNumberOfPeopleElem.value);
sa the tip
var people

u k
//add

n V //divide the total


var totalWithTip = billTotal + (billTotal * 0.1);
a
Mil var dividedTotal = totalWithTip / people;
if (isNaN(dividedTotal)) {
tipOutputElem.innerHTML = "Please input numbers.";
} else if (isFinite(dividedTotal)) {
tipOutputElem.innerHTML = "Each of you will pay:" + dividedTotal;
} else {
tipOutputElem.innerHTML = "Can't divide by 0.";
}
}, false);
}, false);

window.addEventListener("load", function() {
var button = document.getElementById("numberButton");
button.addEventListener("click", function() {
var numberOutput = document.getElementById("numberOutput");
var numberElem = document.getElementById("numberText");
numberOutput.innerHTML = numberElem.value + 20;
}, false);
}, false);

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

Appendix JSConsole Examples


Chapter 10 - Page 23
/lesson05/numbers/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>JavaScript Numbers</title>
<meta charset="UTF-8">
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<link rel="stylesheet" href="style.css">


<script src="code.js"></script>
</head>
<body>
<div>
<h4>Years until you are 100 years old:</h4>
<input type="text" id="ageInput"/>
<input type="button" value="calculate" id="ageButton"/>
<div id="ageOutput">&nbsp;</div>
</div> n s e
i ce
el
<div>
Tip Calculator<br>
a b l
<input type="text" id="tipTotalBill"/>
fer
<input type="text" id="tipNumberOfPeople"/>
a n s
<input type="button" value="calculate" id="tipButton"/>
<div id="tipOutput">&nbsp;</div> n - tr
o
</div>
s an
<div>
) h a deฺ
ฺrs t Gui
Number Input<br>
<input type="range" min="0" max="5" id="numberText"/>
s
@ em uden
<input type="button" value="Check" id="numberButton">
<div id="numberOutput">&nbsp;</div>
</div>
a n S t
</body> s
uk e thi s
ฺ v
an
</html>
s
(
JavaScript URI
n mil to u
a
ksand decode URIs.
Encode
u
anV
Mil /lesson05/uri/code.js
var uri = "http://www.oracle.com/list?order:by name";
var encodedUri = encodeURI(uri);
console.log(encodedUri);
//http://www.oracle.com/list?order:by%20name
var decodedUri = decodeURI(encodedUri);
console.log(decodedUri);
//http://www.oracle.com/list?order:by name

JavaScript Parsing Dates


Parse and validate dates.

/lesson05/dates/code.js
window.addEventListener("load", function() {
var button = document.getElementById("ageButton");
button.addEventListener("click", function() {
var ageOutputElement = document.getElementById("ageOutput");
var monthElement = document.getElementById("monthInput");
var dayElement = document.getElementById("dayInput");
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 24
var nextBirthDay = new Date();
nextBirthDay.setDate(parseInt(dayElement.value));
nextBirthDay.setMonth(parseInt(monthElement.value) - 1);
nextBirthDay.setHours(0);
nextBirthDay.setMinutes(0);
if (nextBirthDay.getTime() < Date.now()) {
//It is on next year.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

nextBirthDay.setFullYear(nextBirthDay.getFullYear() + 1);
}
var milliseconds = nextBirthDay.getTime() - Date.now();
var hours = Math.round(milliseconds / (1000 * 60 * 60));
var days = Math.round(hours / 24);
var result = hours + " hours (" + days + " days) left before birthday!";
ageOutputElement.innerHTML = result;
}, false);
}, false);
n s e
i ce
el
/lesson05/dates/index.html
<!DOCTYPE html>
a b l
<html>
fer
<head>
a n s
<script>parent.window.setDebugConsole();</script>
n - tr
<title>JavaScript Dates</title> o
<meta charset="UTF-8">
s an
<link rel="stylesheet" href="style.css">
) h a deฺ
ฺrs t Gui
<script src="code.js"></script>
</head>
s
<body>
@ em uden
<div>
a n S t
s s
<h4>Hours until your next birthday</h4>
uk e thi
v
Month (1 to 12): <input type="text" id="monthInput"/>

an s
Day (1 to 31): <input type="text" id="dayInput"/>

n (mil to u
<input type="button" value="calculate" id="ageButton"/>
<div id="ageOutput">&nbsp;</div>

u ksa
</div>

n V </body>
a </html>
Mil Exercise: JavaScript String Parsing
Parse strings to get data.

/lesson05/parsing/code.js
var data = "John,Doe,32,1982,10,23,153.25, A ,";
var person = {};

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

person.firstName = splitData[0];
person.lastName = splitData[1];
person.age = parseInt(splitData[2]);
person.credit = parseFloat(splitData[6]);
person.rating = splitData[7].trim();
var year = parseInt(splitData[3]);
var month = parseInt(splitData[4]) - 1;
var day = parseInt(splitData[5]);
person.birthdate = new Date(year, month, day, 0, 0, 0, 0);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 25
JavaScript Regular Expressions
Validate emails with regex.

/lesson05/regexmail/code.js
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function validateEmail() {
var emailElement = document.getElementById("email");
var outputElement = document.getElementById("output");
var emailString = emailElement.value;
var regex = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i;
if (regex.test(emailString)) {
outputElement.innerHTML = "VALID EMAIL";
} else {

}
outputElement.innerHTML = "INVALID EMAIL";
n s e
i ce
el
}

a b l
fer
/lesson05/regexmail/index.html
a n s
<!DOCTYPE html>
n - tr
o
an
<html>
<head>
h s
a deฺ
<script>parent.window.setDebugConsole();</script>
<title>JavaScript REGEX</title> )
ฺrs t Gui
<meta charset="UTF-8"> s
<script src="code.js"></script>
@ em uden
</head>
a n S t
<body> s
uk e thi s
ฺ v
<input type="text" id="email">
an s
mil to u
<input type="button" value="validate" onclick="validateEmail()">

</body>n (
<div id="output"></div>

ksa
</html>
u
n V
a
Mil
Arrays
Examples for Arrays

/lesson05/arrayMethods/code.js
// Array Methods

//push
console.log("*push*");
var months = ["Jan", "Feb", "Mar"];
console.log("months => " + months);
months.push("Apr", "May", "Jun");
console.log("months => " + months); // ["Jan", "Feb", "Mar", "Apr", "May",
"Jun"]

//pop
console.log("*pop*");
var shapes = ["triangle", "circle", "square"];
console.log("shapes => " + shapes);
var shape = shapes.pop();
console.log("shape => " + shape); // "square"
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 26
console.log("shapes => " + shapes); // ["triangle", "circle"]

//splice
console.log("*splice*");
var elements = ["fire", "water", "earth", "air"];
console.log("elements => " + elements);
var elem_deleted = elements.splice(1, 2);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

console.log("elem_deleted => " + elem_deleted); // ["water", "earth"]


console.log("elements => " + elements); // ["fire", "air"]

//shift
console.log("*shift*");
var shapes = ["triangle", "circle", "square"];
console.log("shapes => " + shapes);
var shape = shapes.shift();
console.log("shape => " + shape); // "triangle"
console.log("shapes => " + shapes); // ["circle", "square"]
n s e
i ce
//unshift
b l el
console.log("*unshift*");
fer a
var elements = ["fire", "water", "earth", "air"];
a n s
-tr
console.log("elements => " + elements);
elements.unshift("fifth element");
o n
an
console.log("elements => " + elements); // ["fifth element", "fire", "water",
"earth", "air"]
h s
a deฺ
//reduce )
ฺrs t Gui
s
em uden
console.log("*reduce*");
var numbers = [100, 10, 10, 10, 5];
a n @
console.log("numbers => " + numbers);
S t
s
uk e thi s
var result = numbers.reduce(function(prevValue, currentValue) {
return prevValue -ฺvcurrentValue;
});
m i lan=>to" u+ sresult); // 65
(
console.log("result
n
ks a
u
//indexOf
V items = ["pencil", "scissors", "eraser", "tape"];
console.log("*indexOf*");
anvar
Mil console.log("items => " + items);
var index = items.indexOf("eraser");
console.log("index => " + index); // 2
index = items.indexOf("glue");
console.log("index => " + index); // -1

JavaScript Arrays
Use arrays as collections.

/lesson05/arrays/code.js
window.addEventListener("load", function() {
var button = document.getElementById("listButton");
button.addEventListener("click", function() {
var outputElement = document.getElementById("outputElement");
var listElement = document.getElementById("listElement");
var result = [];
for (var i = 0; i < listElement.length; i++) {
if (listElement[i].selected) {
result.push(listElement[i].value);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 27
}
}
outputElement.innerHTML = result.join(", ");
}, false);
}, false);

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

<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>JavaScript Arrays</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="code.js"></script>
</head>
n s e
<body>
i ce
<div>
<h4>Select elements (use CTRL to select multiple)</h4> b l el
<select id="listElement" size="5" multiple="multiple">
fer a
<option value="JavaScript">JavaScript</option>
a n s
<option value="HTML">HTML</option>
n - tr
<option value="CSS">CSS</option> o
<option value="Java SE">Java SE</option>
s an
<option value="Java EE">Java EE</option>
) h a deฺ
ฺrs t Gui
<option value="Java ME">Java ME</option>
s
<option value="Java FX">Java FX</option>
</select>
@ em uden
a n S t
<input type="button" value="calculate" id="listButton"/>
s s
<div id="outputElement">&nbsp;</div>
uk e thi
</div>
ฺ v
</body>
an s
</html>
n ( mil to u
a
ks JavaScript Arrays
Exercise:
u
anV
Mil Use array operations.

/lesson05/more_arrays/code.js
var animals = ["dog", "cat", "horse", "duck", "rabbit", "canary", "fox"];
var numbers = [1, 4, 7, 8, 1, 6, 4, 8, 3, 2, 1, 9, 6];
var floats = [1.5, 4.4, 7.8, 8.1, 1.6, 6.8, 4.4, 8.9];
var colors = ["red", "green", "blue", "yellow", "cyan", "magenta"];
var people = [{name: "Ed"}, {name: "John"}, {name: "Peter"}, {name: "Mike"}];
var functions = [];

animals.pop();
animals.pop();

numbers.push(10);

floats.splice(2, 1);

colors.splice(3, 1, "orange");

people = [];
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 28
// people.splice(0,people.length);
// people.length=0;
// while(people.length>0){people.pop();}

functions.push(function() {
return true;
});
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Object Methods
Examples for Object Methods

/lesson05/objectMethods/code.js
console.log("**Static Object Methods**");
// Static Object Methods
var obj = {a: 45};
Object.defineProperty(obj, "double_a", {get: function() { n s e
i ce
el
return this.a * 2;
}});
a b l
Object.defineProperty(obj, "modify_a", {set: function(x) {
fer
this.a -= x;
a n s
}});
n - tr
console.log("obj.a => " + obj.a); n o
console.log("obj.double_a => " + obj.double_a); s a
) h a deฺ
ฺrs t Gui
obj.modify_a = 40;
console.log("obj.a => " + obj.a);
s
em uden
console.log("obj.double_a => " + obj.double_a);

a n @ S t
s
uk e thi s
ฺ v
m i lan to us
n (
ks a
u
anV
Mil

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

Appendix JSConsole Examples


Chapter 10 - Page 29
Lesson 6 Application Data
Exercise: JSON Parsing and Generation
Convert objects to JSON strings and back.

/lesson06/jsonEx/code.js
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

// Create the following object in JSON:


// {name:"John", age: 32}
var jsonObject1 = "{\"name\":\"John\", \"age\": 32}";

// Create the following array in JSON:


// [1,2,3]
var jsonArray1 = "[1,2,3]";

// Create the following object in JSON:


n s e
// {name:"John", age: 32, level:"A", scores:{math:100, history:75}}
i ce
var jsonObject2 = "{\"name\":\"John\", \"age\": 32, \"level\":\"A\",
b l el
\"scores\":{\"math\":100, \"history\":75}}";
fer a
// Create the following array in JSON
a n s
// [1,2,"a","b",{name:"Ed"}]
o n -tr
var jsonArray2 = "[1,2,\"a\",\"b\",{\"name\":\"Ed\"}]";
a n
h
//parse the object using JSON.parse with the string s eฺ
a dabove.
var object2 = JSON.parse(jsonObject2); )
ฺrs t Gu i
s
em uden
//log the stringified version of object2
@
n
console.log(JSON.stringify(object2));
a S t
s
uk e thi s
Cookies ฺ v
i lan to us
Simple cookie example
m
n (
ks a
/lesson06/cookies/code.js
u
an Vdocument.getElementById("cookie").innerHTML
window.addEventListener("load", function() {

Mil
= document.cookie;
var cookieStrings = document.cookie.split(";");
var cookies = {};
for (var i = 0; i < cookieStrings.length; i++) {
var rawCookie = cookieStrings[i].trim().split("=");
cookies[rawCookie[0]] = rawCookie[1];
console.log(rawCookie[0] + " --> " + rawCookie[1]);
}
});
function setCookie() {
var name = document.getElementById("name").value;
var value = document.getElementById("value").value;
document.cookie = name + "=" + value;
}
function clearCookie() {
var name = document.getElementById("name").value;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}

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

Appendix JSConsole Examples


Chapter 10 - Page 30
/lesson06/cookies/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Cookies test</title>
<meta charset="UTF-8">
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<script src="code.js"></script>
</head>
<body>
Cookies:<span id="cookie"></span><br>
Name:<input type="text" id="name">
Value:<input type="text" id="value">
<input type="button" value="Set cookie" onclick="setCookie();">
<input type="button" value="Clear cookie" onclick="clearCookie();">
</html>
n s e
i ce
Exercise: Local Storage
b l el
Save the state of an application.
fer a
/lesson06/localStorageEx/code.js a n s
n - tr
var storedObject = {};
o
window.addEventListener("load", function() {
s an
) h a deฺ
//Get the stored object from the localStorage and parse using JSON

ฺrs t Gui
var storedData = localStorage.getItem("storedObject");
s
storedObject = JSON.parse(storedData);
if (!storedObject) {
storedObject = {}; @ em uden
a n S t
}
s
uk e thi s
document.getElementById("storage").innerHTML =
ฺ v
an
JSON.stringify(storedObject);
s
});
n (mil to u
function addProperty() {

u ksa
var name = document.getElementById("name").value;
var value = document.getElementById("value").value;
n V //set the property in the stored object and save the JSON representation in
a
Mil the
//Local Storage
storedObject[name] = value;
localStorage.setItem("storedObject", JSON.stringify(storedObject));
}
function removeProperty() {
var name = document.getElementById("name").value;
//Remove the property in the stored object and save the JSON representation
in the
//Local Storage
delete storedObject[name];
localStorage.setItem("storedObject", JSON.stringify(storedObject));
}

/lesson06/localStorageEx/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 31
<title>Local Storage</title>
<meta charset="UTF-8">
<script src="code.js"></script>
</head>
<body>
LocalStorage:<span id="storage"></span><br>
Name:<input type="text" id="name">
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Value:<input type="text" id="value">


<input type="button" value="Add property" onclick="addProperty();">
<input type="button" value="Remove property" onclick="removeProperty();">
</html>

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

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

Appendix JSConsole Examples


Chapter 10 - Page 32
Lesson 7 Style Applications Using CSS3 and JavaScript
CSS Examples
Change the style of the web page.

/lesson07/css_examples/styles.css
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

/lesson07/css_examples/index.html
<!DOCTYPE html>
<html>
<head>
<title>The Next Big Front-End Conference</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
</head>
n s e
i ce
el
<body>
<header>
a b l
<h1>The Next Big Conference for Front-End Developers</h1>
fer
<h2>Join us this year</h2>
a n s
<nav>
<ul>
n - tr
o
an
<li><a href="*">Home</a></li>

h s
<li><a href="#section-1">Speakers</a></li>
a deฺ
<li><a href="#section-2">Workshops</a></li>
)
ฺrs t Gui
<li><a href="#section-3">Submit Proposal</a></li>
s
em uden
</ul>
</nav>
</header>
a n @ S t
s
uk e thi
<section id="section-1"> s
<article> ฺ v
an s
mil to u
<header>

n (
<h1>Speakers</h1>

ksa
</header>

V u <p>Text</p>

an <p>More Text</p>

Mil
<p>Even More Text</p>
<p>Some Text</p>
</article>
</section>
<section id="section-2">
<article>
<header>
<h1>Workshops</h1>
</header>
<p>Text</p>
<p>More Text</p>
<p>Even More Text</p>
<p>Some Text</p>
</article>
</section>
<section id="section-3">
<article>
<header>
<h1>Submit Proposal</h1>
</header>
<p>Text</p>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 33
<p>More Text</p>
<p>Even More Text</p>
<p>Some Text</p>
<form name="proposalForm">
<fieldset>
<p>
<label for="name">Name:(required)</label>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<input type="text" name="name" id="name" required>


</p>
<p>
<label for="email">Email:(required)</label>
<input type="email" name="email" id="email">
</p>
<p><label for="file">Send us a document with the
abstract:</label></p>
<input type="file" name="file" id="file">
<p><input type="submit" name="submit" value="submit"></p>
n s e
</fieldset>
i ce
</form>
b l el
</article>
fer a
</section>
a n s
tr
<aside>
<h1>Ads</h1>
o n -
an
<p class="advertising">UI/UX advertising</p>
</aside>
<footer> h s
a deฺ
)
ฺrs t Gui
<p class="copyright user-groups">&copy; 2014 Front End User Groups</p>
s
em uden
</footer>
</body>
</html>
a n @ S t
s
uk e thi s
CSS Box ฺ v
m i
Change the position laofnthetbox.
o us
n (
ks a
/lesson07/css_box/styles.css
u
anpV{
Mil
display: block;
}

.box {
width: 140px;
height: 100px;
margin: 24px 48px; /* 24px 48px 24px 48px */
border: 1px solid blue;
padding: 12px 18px 6px; /* 12px 18px 6px 18px */
}

/lesson07/css_box/index.html
<!DOCTYPE html>
<html>
<head>
<title>The Box</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
</head>
<body>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 34
<section id="section-1">
<div class="box">
<h1>I am in a box</h1>
</div>
<p>Text</p>
<p>More Text</p>
<p>Even More Text</p>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<p>Some Text</p>
</section>
</body>
</html>

Media Queries
Test media queries by changing the screen size.

/lesson07/media_queries/styles.css
n s e
i ce
el
body {
background-color: grey;
a b l
}
fer
.landscape {
a n s
}
display: none;
n - tr
o
@media screen and (max-width: 1368px) {
s an
body {
) h a deฺ
ฺrs t Gui
background-color: lightsteelblue;
}
s
em uden
}

body {
a n @
@media screen and (max-width: 960px) {
S t
s
uk e thi
background-color: yellow; s
ฺ v
an
}
s
mil to u
}
(
@media screen and (max-width: 768px) {
n
ksa
body {

V u background-color: orange;

an }

Mil
}
@media screen and (max-width: 600px) {
body {
background-color: red;
}
}
@media screen and (max-width: 320px) {
body {
background-color: green;
}
}
@media screen and (orientation: landscape){
.landscape {
display: block;
}
}
@media screen and (orientation: portrait){
.landscape {
display: none;
}

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

Appendix JSConsole Examples


Chapter 10 - Page 35
}

/lesson07/media_queries/index.html
<!DOCTYPE html>
<html>
<head>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<title>Media Queries</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>Text</p>
<footer>
<div class="landscape">
<h2>Landscape Orientation</h2>
</div>
n s e
</footer>
i ce
</body>
</html> b l el
fer a
Multi-Column a n s
Practice a multi-column layout. n - tr
o
s an
/lesson07/multi-column/styles.css
) h a deฺ
ฺrs t Gui
.columns {
-webkit-column-width: 13em; s
-webkit-column-gap: 1em;
@ em en
#000;tud
-moz-column-width: 13em;sa
n
-webkit-column-rule: 1px solid
S
-moz-column-gap: 1em;uk th i s
v se #000;
-moz-column-rule:nฺ1px solid
a
column-width: il13em; o u
n (
column-gap:
m1em;
t
ks a
column-rule: 1px solid #000;
}Vu
an
Mil
/lesson07/multi-column/index.html
<!DOCTYPE html>
<html>
<head>
<title>Multi-column</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="columns">
<p>Text.</p>
</div>
</body>
</html>

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

Appendix JSConsole Examples


Chapter 10 - Page 36
CSS and JavaScript
Modify styles dynamically with JavaScript.

/lesson07/css_javascript/code.js
var changeBox = function(event) {
console.log("changeBox function called");
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var box = document.getElementById("box");


box.style.backgroundColor = "#ff9966";
box.style.width = "280px";
box.style.float = "left";
box.style.borderStyle = "dotted";
};

/lesson07/css_javascript/styles.css
p {
n s e
ce
display: block;
}
eli
a b l
#box {
fer
width: 140px;
a n s
height: 100px;
n - tr
margin: 24px 48px; /* 24px 48px 24px 48px */
o
border: 2px solid blue;
s an
) h a deฺ
padding: 12px 18px 6px; /* 12px 18px 6px 18px */

ฺrs t Gui
}

/lesson07/css_javascript/index.htmlem
s
@ u d en
<!DOCTYPE html>
a n S t
<html> s
uk e thi s
<head>
ฺ v
i lan to us
<title>The Box</title>
m
(
<meta charset="UTF-8">
<link n
a rel="stylesheet" href="styles.css">
ks src="code.js"></script>
u<script

an V<body>
</head>

Mil <button onclick="changeBox()">Change box style</button>


<section id="section-1">
<div id="box">
<h1>I am in a box</h1>
</div>
<p>Text</p>
<p>More Text</p>
<p>Even More Text</p>
<p>Some Text</p>
</section>
</body>
</html>

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

Appendix JSConsole Examples


Chapter 10 - Page 37
Lesson 8 Advanced JavaScript
JavaScript Variables and Functions
Variables and functions

/lesson08/varfunctions/code.js
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

try {
fun();
} catch (e) {
console.log("error with function:" + e);
}
try {
varfun();
} catch (e) {
console.log("error with function as variable: " + e);
n s e
}
i ce
b l el
var varfun = function() {
console.log("function as variable");
fer a
};
a n s
n - tr
o
an
function fun() {
console.log("Function");
}
h s
a deฺ
)
ฺrs t Gui
try { s
fun();
@ em uden
} catch (e) {
console.log("error with s a n S t
uk e thi s
function:" + e);
}
ฺ v
varfun(); mil
try {
an o us
n ({ t
ks a
} catch (e)
console.log("error with function as variable: " + e);
}Vu
an
Mil // inner function
console.log("*inner function*");
function outer() {
var x = "I am declared in the outer function";
function inner() {
console.log(x);
}
inner();
}

outer();

console.log("*call and apply methods*");


// call and apply methods
function myFunction() {
console.log(this.myProperty);
}
var myObj = {
myProperty: 15
};
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 38
myFunction.call(myObj); // 15
myFunction.apply(myObj); // 15

console.log("**Function Methods**");
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

// Function Methods
// Function.prototype.toString()
console.log("*Function.prototype.toString()*");
console.log("outer.toString() => " + outer.toString());
// Function.prototype.bind()
console.log("*Function.prototype.bind()*");
var myObj = {
myVar: "Hello there!",
greet: function() {
innerGreet = function(name) {
n s e
console.log(this.myVar + name);
i ce
};
b l el
innerGreet.bind(this, " Duke")();
fer a
}
a n s
tr
};

o n -
an
myObj.greet();

/lesson08/varfunctions/index.html h s
a deฺ
ฺ )
rs t Gui
<!DOCTYPE html>
s
<html>
@ em uden
<head>
a n S t
s s
<script>parent.window.setDebugConsole();</script>
uk e thi
v
<title>JavaScript functions</title>

m i lan to us
<meta charset="UTF-8">
<script src="code.js"></script>
</head>
n (
ks a
<body>JavaScript code. View Console</body>
u
nV
</html>
a
Mil Default Values
Default values for function parameters

/lesson08/defaultValues/code.js
function greet(message) {
message = message || "NO MESSAGE";
console.log("greet-->" + message);
}
greet();
greet(null);
greet("Hello!");
greet(false);
greet(true);
greet(123123);

function paramTest() {
var message = "ParamTest-->";
for (i = 0; i < arguments.length; i++) {
message += "[" + arguments[i] + "]";
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 39
}
console.log(message);
}
paramTest();
paramTest(1, 2);
paramTest("a", null, undefined, false, 3);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

Array Extended API


Array API with callbacks

/lesson08/arrays/code.js
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.toString = function() { n s e
i ce
el
return this.name + "[" + this.age + "]";
}
a b l
fer
var persons = [];
a n s
persons.push(new Person("Ed", 31));
persons.push(new Person("John", 22)); n - tr
o
persons.push(new Person("Peter", 44));
s an
persons.push(new Person("Joseph", 12));
) h a deฺ
ฺrs t Gui
persons.push(new Person("Richard", 18));
printArray("--unsorted--", persons);
s
// SORT BY NAME
@ em uden
persons.sort(function(personA,
an personB)
S t{
return personA.name > k s
u e thi s
personB.name ? 1 : -1;
ฺ v
lan bytoname--",
});
i
printArray("--Sorted
m us persons);
(
k s aBYn AGE
u
// SORT
V
an persons.sort(function(personA, personB) {

Mil
return personA.age > personB.age;
});
printArray("--Sorted by age--", persons);

var every10yo = persons.every(function(person) {


return person.age > 10;
});
console.log("Everyone is at least 10 years old?: " + every10yo);

var some18yo = persons.some(function(person) {


return person.age > 18;
});
console.log("Is someone over 18 years?: " + some18yo);

var grownUps = persons.filter(function(person) {


return person.age > 18;
});
printArray("--grown ups--", grownUps);

var ages = persons.map(function(person) {


return person.age;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 40
});
printArray("--ages--", ages);

var totalAge = ages.reduce(function(prevValue, currValue) {


return prevValue + currValue;
}, 0);
console.log("Total age:" + totalAge);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var grownUpAgeTotal = persons.filter(function(person) {


return person.age > 18;
})
.map(function(person) {
return person.age;
})
.reduce(function(prevValue, currValue) {
return prevValue + currValue;
}, 0);
n s e
console.log("Total age of grown ups:" + grownUpAgeTotal);
i ce
b l el
fer a
a n s
tr
//----- UTILITY METHODS
function printArray(header, array) {
o n -
an
console.log(header);
array.forEach(function(item, index) {
if (item.toString) { h s
a deฺ
)
ฺrs t Gui
console.log(index + ":" + item.toString());
s
em uden
} else {
console.log(index + ":" + item);
}
a n @ S t
}); s
uk e thi s
} ฺ v
an s
(mil to u
/lesson08/arrays/index.html
n
ksa
<!DOCTYPE html>
u
n V<html>
a <head>
Mil <script>parent.window.setDebugConsole();</script>
<title>JavaScript functions</title>
<meta charset="UTF-8">
<script src="code.js"></script>
</head>
<body>JavaScript code. View Console</body>
</html>

Exercise: Array Extended API


Use array functions to filter, map, and reduce.

/lesson08/exarrays/code.js
function Item(name, price, tags) {
this.name = name;
this.price = price;
this.tags = tags;
}
var items = [];
items.push(new Item("Cellphone", 99.99, ["electronics", "computing"]));
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 41
items.push(new Item("Computer", 250.54, ["computing"]));
items.push(new Item("Book", 15.25, ["printed material"]));
items.push(new Item("Magazine", 8.52, ["printed material"]));
items.push(new Item("Tablet", 150.54, ["electronics", "computing"]));
items.push(new Item("Speaker", 55.21, ["electronics"]));

// Calculate the total of all items.


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

var total = items.map(function(item) {


return item.price;
}).reduce(function(prevVal, currVal) {
return prevVal + currVal;
}, 0);
// Calculate the total of all electronics.
var electronicsTotal = items.filter(function(item) {
return item.tags.some(function(tag) {
return tag === "electronics";
});
n s e
}).map(function(item) {
i ce
return item.price;
b l el
}).reduce(function(prevVal, currVal) {
fer a
return prevVal + currVal;
a n s
tr
}, 0);
// Create an object with the count of all the tags.
o n -
an
var allTags = {};
items.forEach(function(item) {
item.tags.forEach(function(tag) { h s
a deฺ
allTags[tag] = allTags[tag] || 0; )
ฺrs t Gui
s
em uden
allTags[tag]++;
});
});
a n @ S t
s
uk e thi s
ฺ v
/lesson08/exarrays/index.html
m i lan to us
Closures n (
Review
a
ksclosures.
u
anV
Mil /lesson08/closures/code.js
// Closure variable scope
function trickyAdd(number1, number2) {
function doAdd() {
return number1 + number2;
}
number1 += 1;
number2 += 2;
return doAdd();
};
console.log(trickyAdd(1, 1));

// inner function (from lesson 03)


console.log("*inner function*");
function outer() {
var x = "I am declared in the outer function";
function inner() {
console.log(x);
}
inner();

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

Appendix JSConsole Examples


Chapter 10 - Page 42
}

outer();

// this and that


console.log("*this and that*");
var myObj = {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

myVar: "Hello there!",


greet: function() {
that = this;
innerGreet = function() {
console.log(that.myVar);
};
innerGreet();
}
};
n s e
myObj.greet();
i ce
b l el
Private Scope
fer a
Create objects with private functions.
a n s
n - tr
o
an
/lesson08/privateScope/code.js
function createObject() {
h s
a deฺ
var value = 0;
function sum(a, b) { )
ฺrs t Gui
s
em uden
return a + b;
}
;
a n @ S t
return { s
uk{ e thi s
ฺ v
lanval);
add2: function(val)
i
return sum(2, u s
m t o
( sum(10, val);
}, add10: function(val) {
n
ksa
return
u},

an V increment: function(val) {
Mil
value += val;
},
getValue: function() {
return value;
}};
}
var object = createObject();
console.log(object.value); // undefined
console.log(object.getValue()); //0
console.log(object.increment(5));
console.log(object.getValue()); // 5
console.log(object.add2(5)); // 7
console.log(object.add10(10)); //20

Returning Functions
Create functions inside a function.

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

Appendix JSConsole Examples


Chapter 10 - Page 43
/lesson08/returnFunctions/code.js
function createIncrementByNumber(number) {
return function(x) {
return number + x;
};
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var inc = createIncrementByNumber(2);


console.log("inc(3)=" + inc(3)); // 5
console.log("inc(10)=" + inc(10)); //12

var inc2 = createIncrementByNumber(10);


console.log("inc2(3)=" + inc2(3)); // 13
console.log("inc2(10)=" + inc2(10)); // 20

Loops with closures


n s e
Looping with closures
i ce
b l el
/lesson08/loopsClosures/code.js
fer a
var functionArray = [];
a n s
for (i = 0; i < 5; i++) {
n - tr
functionArray.push(
o
function() {
s an
console.log(i);
) h a deฺ
ฺrs t Gui
});
}
s
@ em uden
for (t = 0; t < functionArray.length; t++) {
functionArray[t](); // always prints 5!
a n S t
}
s s
console.log("FIXED n ฺ vuk se thi
VERSION");
ila= [];to{u
var functionArray
for (i = 0; (im
an
< 5; i++)

u k s
(function(number) {
functionArray.push(
anV function() {
Mil }
console.log(number);

);
}(i));
}
for (t = 0; t < functionArray.length; t++) {
functionArray[t](); // prints 0 to 4
}

Modules
Module code example

/lesson08/modules/code.js
window.addEventListener("load", function() {
console.log(module.getName());
console.log(module.publicVariable);
module.method();
module.extension();
});
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 44
/lesson08/modules/module.js
var module = (function(module) {
module.publicVariable = "a";
var name = "module 1";
module.method = function() {
console.log("METHOD!");
};
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

module.getName = function() {
return name;
};
return module;
}(module || {}));

/lesson08/modules/module_ext.js
var module = (function(module) {
var name = "EXT 1";
n s e
module.extension = function() {
i ce
console.log("EXTENSION: " + name);
b l el
};
return module;
fer a
}(module || {}));
a n s
n - tr
o
Prototypes
s an
JavaScript Prototype Inheritance
) h a deฺ
/lesson08/prototypes/code.js s ฺrs t Gui
function A() {
@ em uden
}
a n S t
var inst1 = new A(); s
k thi s
var inst2 = new A(); vu
a ฺ
n use
try {
i l to
(m
console.log(inst1.getName());
n
sa
} catch (ex) {

}V u k
console.log("Function does not exist yet");

anA.prototype.getName = function() {
Mil };
return "PROTO A";

console.log(inst1.getName());
console.log(inst2.getName());

function B() {
}
;
B.prototype = new A();
var b = new B();
console.log(b.getName());

Drag and Drop


HTML5 Drag and Drop JavaScript Events

/lesson08/dnd/code.js
function drag(event) {
event.dataTransfer.setData("Text", "Dragged");
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 45
function dragOver(event) {
event.preventDefault();
}

function drop(event) {
event.preventDefault();
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

alert(event.dataTransfer.getData("Text"));
}

/lesson08/dnd/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Drag and Drop</title>
n s e
<meta charset="UTF-8">
i ce
<script src="code.js"></script>
</head> b l el
<body>
fer a
<div style="border: 1px solid blue;" ondragstart="drag(event)"
a n s
draggable="true">DRAG ME!</div>
n - tr
<br> o
an
<div style="border: 1px solid red;" ondragover="dragOver(event)"
s
ondrop="drop(event)">DROP HERE!</div>
) h a deฺ
ฺrs t Gui
</body>
</html>
s
@ em uden
Timeouts and Intervals
a n S t
s
uk e thi
Timeout and interval functions s
ฺ v
i lan to us
/lesson08/timeouts/code.js
m
n
var timeoutId;(
a
ks startTimeout() {
var intervalId;
u
n Vconsole.log("setting timeout");
function
a
Mil timeoutId = setTimeout(function() {
console.log("TIMEOUT!");
}, 3000);
console.log("After Timeout");
console.log("timeout set:" + timeoutId);
}
function cancelTimeout() {
clearTimeout(timeoutId);
}
function startInterval() {
if (!intervalId) {
console.log("setting interval");
intervalId = setInterval(function() {
console.log("INTERVAL!");
}, 1000);
console.log("After Interval");
console.log("interval set:" + intervalId);
}
}
function cancelInterval() {
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 46
clearInterval(intervalId);
intervalId = undefined;
}

/lesson08/timeouts/index.html
<!DOCTYPE html>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Timeouts and intervals</title>
<meta charset="UTF-8">
<script src="code.js"></script>
</head>
<body>
<input type="button" value="Start Timeout" onclick="startTimeout();">
<input type="button" value="Cancel Timeout" onclick="cancelTimeout();">
n s e
<input type="button" value="Start Interval" onclick="startInterval();">
i ce
<input type="button" value="Cancel Interval" onclick="cancelInterval();">
</body> b l el
</html>
fer a
a n s
Workers
n - tr
o
JavaScript workers
s an
) h a deฺ
ฺrs t Gui
/lesson08/workers/code.js
function startWorker() { s
em{ uden
var worker = new Worker("worker.js");
@
s a nworker"S+t event.data);
worker.onmessage = function(event)

uk e this
console.log("Message from
}
ฺ v
l an oworker...");
console.log("Starting
i u s
m
( i < 10; ti++) {
worker.postMessage("");
for (i =n 0;
ks a
console.log("Log:" + i);
u
n}V
}
a
Mil
/lesson08/workers/worker.js
for (i = 0; i < 10; i++) {
postMessage("" + i);
}

/lesson08/workers/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Workers</title>
<meta charset="UTF-8">
<script src="code.js"></script>
</head>
<body>
<input type="button" value="Start Worker" onclick="startWorker();">
</body>
</html>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 47
HTML5 Canvas Strokes
Canvas strokes

/lesson08/canvas_strokes/code.js
window.addEventListener("load", function() {
var canvas = document.getElementById("html5canvas");
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var ctx = canvas.getContext("2d");

//Set Stroke properties


ctx.strokeStyle = "#FF3333"; //color
ctx.lineWidth = 10; //line width
ctx.lineCap = "butt"; //line cap
// Paint a line
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.lineTo(10, 110);
n s e
ctx.stroke();
i ce
b l el
//Set Stroke properties
fer a
ctx.strokeStyle = "#DD4444"; //color
ctx.lineWidth = 10; //line width
a n s
ctx.lineCap = "round"; //line cap
n - tr
o
an
// Paint a line
ctx.beginPath();
ctx.moveTo(30, 10);
h s
a deฺ
ctx.lineTo(30, 110); )
ฺrs t Gui
ctx.stroke(); s
@ em uden
//Set Stroke properties
a n //color
S t
s
uk ewidth
ctx.strokeStyle = "#DD5533";
hi s
ctx.lineWidth = 10;v//line
ฺ t
i lan to u//line
ctx.lineCap = "square";
// Paint a m
s cap

n ( line

ks a
ctx.beginPath();
ctx.moveTo(50, 10);
u
n Vctx.stroke();
ctx.lineTo(50, 110);
a
Mil //paint some guides.
ctx.strokeStyle = "#444444";
ctx.lineWidth = 1; //line width
ctx.lineCap = "butt"; //line cap
ctx.beginPath();
ctx.moveTo(0, 10);
ctx.lineTo(60, 10);
ctx.moveTo(0, 110);
ctx.lineTo(60, 110);
ctx.stroke();

});

/lesson08/canvas_strokes/index.html
<!DOCTYPE html>
<html>
<head>

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

Appendix JSConsole Examples


Chapter 10 - Page 48
<script>parent.window.setDebugConsole();</script>
<title>Canvas Strokes</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="code.js"></script>
</head>
<body>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<canvas id="html5canvas" width="300" height="200"></canvas>


</body>
</html>

HTML5 Canvas Fills


Canvas fills

/lesson08/canvas_fill/code.js
window.addEventListener("load", function() { n s e
i ce
el
var canvas = document.getElementById("html5canvas");
var ctx = canvas.getContext("2d");
a b l
fer
//add a guide.
a n s
ctx.fillStyle = "#DDDDFF"; //color
ctx.fillRect(0, 0, 300, 50); n - tr
o
s an
//Solid fill
) h a deฺ
ฺrs t Gui
ctx.fillStyle = "#FF3333"; //color
// Fill Rectangle
s
em uden
ctx.fillRect(10, 10, 80, 80);

//Solid fill
a n @ S t
s
k thi s
// Fill Rectangle ฺvu
ctx.fillStyle = "rgba(0,0,0,0.3)"; //color

i l
ctx.fillRect(100,an10,o80,
u se80);
n (m t
a
s = ctx.createLinearGradient(200, 50, 280, 50);
//Gradient
varkgrd
fill
u
an Vgrd.addColorStop(0, "#000000");
Mil
grd.addColorStop(0.30, "#33AA33");
grd.addColorStop(1, "#FFFFFF");
ctx.fillStyle = grd;
ctx.fillRect(200, 10, 80, 80);

});

/lesson08/canvas_fill/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Canvas Fills</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="code.js"></script>
</head>
<body>
<canvas id="html5canvas" width="300" height="200"> </canvas>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 49
</body>
</html>

HTML5 Canvas Text


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

/lesson08/canvas_text/code.js
window.addEventListener("load", function() {
var canvas = document.getElementById("html5canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#000033"; //color
ctx.strokeStyle = "#222222";

ctx.font = "12px Arial";


ctx.fillText("HELLO!", 10, 10);
n s e
i ce
el
//paint some guides
ctx.strokeStyle = "#CCCCCC";
a b l
ctx.beginPath();
fer
ctx.moveTo(0, 10);
a n s
ctx.lineTo(200, 10);
ctx.moveTo(10, 0); n - tr
o
ctx.lineTo(10, 200);
s an
ctx.stroke();
) h a deฺ
ฺrs t Gui
});

s
/lesson08/canvas_text/index.html @ em uden
a n S t
<!DOCTYPE html> s
uk e thi s
<html>
ฺ v
<head>
m i lan to us
n (
<script>parent.window.setDebugConsole();</script>
<title>Canvas Text</title>
s a
k rel="stylesheet" href="style.css">
<meta charset="UTF-8">
V u<link
an <script src="code.js"></script>
Mil </head>
<body>
<canvas id="html5canvas" width="400" height="200"> </canvas>
</body>
</html>

HTML5 Canvas Basic Paths


Canvas basic paths

/lesson08/canvas_path1/code.js
window.addEventListener("load", function() {
var canvas = document.getElementById("html5canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#DDDDFF"; //color
ctx.strokeStyle = "#222222";

ctx.beginPath();
ctx.moveTo(10, 110);
ctx.lineTo(60, 10);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 50
ctx.lineTo(110, 110);
ctx.lineTo(10, 110);
ctx.fill();
ctx.stroke();
});
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

/lesson08/canvas_path1/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Canvas Simple paths</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="code.js"></script>
n s e
</head>
i ce
<body>
<canvas id="html5canvas" width="300" height="200"></canvas> b l el
</body>
fer a
</html>
a n s
n - tr
HTML5 Canvas Curves o
Canvas curves s an
) h a deฺ
/lesson08/canvas_curves/code.js s ฺrs t Gui
em ude{n
window.addEventListener("load", function()
@
n t
var canvas = document.getElementById("html5canvas");
a S
s hi
uk e//color
var ctx = canvas.getContext("2d");
s
ฺ v
ctx.fillStyle = "#333333"; t
m i la=n"#000000";
t o u s
n (
ctx.strokeStyle
ctx.beginPath();
ks a
ctx.moveTo(10, 10);
u
n Vctx.stroke();
ctx.quadraticCurveTo(30, 50, 100, 10);
a
Mil paintDotText(ctx, "#00FF00", 10, 10);
paintDotText(ctx, "#FF0000", 100, 10);
paintDotText(ctx, "#0000FF", 30, 50);

ctx.beginPath();
ctx.moveTo(210, 40);
ctx.bezierCurveTo(230, 150, 280, 50, 300, 110);
ctx.stroke();
paintDotText(ctx, "#00FF00", 210, 40);
paintDotText(ctx, "#FF0000", 300, 110);
paintDotText(ctx, "#3333FF", 230, 150);
paintDotText(ctx, "#000033", 280, 50);

});

function paintDotText(ctx, color, x, y) {


ctx.fillStyle = color;
ctx.fillRect(x - 1, y - 1, 3, 3);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 51
ctx.fillStyle = "#333333";
ctx.fillText(x + "," + y, x - 10, y + 10);
}

/lesson08/canvas_curves/index.html
<!DOCTYPE html>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Canvas Curves</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="code.js"></script>
</head>
<body>
<canvas id="html5canvas" width="400" height="200"></canvas>
n s e
</body>
i ce
</html>
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

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

Appendix JSConsole Examples


Chapter 10 - Page 52
Lesson 9 AJAX and WebSocket
Exercise: AJAX
Create simple AJAX calls.

/lesson09/ajax/code.js
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function loadData() {
document.getElementById("content").innerHTML = "LOADING";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "data/data.json", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var personData = JSON.parse(xmlhttp.responseText);
var text = "Name:";
text += personData.name;
n s e
text += "<br>";
i ce
text += "Age:";
b l el
text += personData.age;
text += "<br>";
fer a
text += "Hobbies:";
a n s
text += personData.hobbies.join(", ");
n - tr
o
an
document.getElementById("content").innerHTML = text;
}
};
h s
a deฺ
xmlhttp.send(); )
ฺrs t Gui
} s
@ em uden
/lesson09/ajax/data/data.jsonan S t
{ s
uk e thi s
ฺ v
lan to us
"name": "Jonh Doe",
"age": 32,
m i
"hobbies":( ["Music", "Movies"]
}
k s an
V u
an /lesson09/ajax/index.html
Mil <!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>Exercise: AJAX</title>
<meta charset="UTF-8">
<script src="code.js"></script>
</head>
<body>
<input type="button" value="Load Data" onclick="loadData();">
<div id="content">Display info here when button is clicked!</div>
</body>
</html>

REST and AJAX


Restful services and AJAX

/lesson09/rest/code.js
window.addEventListener("load", function() {
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 53
hideAll();
});

function showAdd() {
hideAll();
document.getElementById("sec_add").setAttribute("style", "");
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

function showList() {
hideAll();
document.getElementById("sec_loading").setAttribute("style", "");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost:8080/JSConsole/rest/cars/", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var cars = JSON.parse(xmlhttp.responseText);
var listElement = document.getElementById("carList");
while (listElement.firstChild) {
n s e
listElement.removeChild(listElement.firstChild);
i ce
}
b l el
for (i = 0; i < cars.length; i++) {
fer a
var listItem = document.createElement("li");
a n s
tr
var anchor = document.createElement("a");
anchor.setAttribute("href", "#");
o n -
an
(function(id) {

showDetail(id); h s
anchor.addEventListener("click", function() {
a deฺ
}); )
ฺrs t Gui
s
em uden
}(cars[i]));
anchor.appendChild(document.createTextNode(cars[i]));
a n @
listItem.appendChild(anchor);
S t
s
uk e thi s
listElement.appendChild(listItem);
} ฺ v
an s
mil to u
hideAll();
(
document.getElementById("sec_list").setAttribute("style", "");
n
ksa
}

V u};
xmlhttp.send();
an
Mil
}
function showDetail(id) {
hideAll();
document.getElementById("sec_loading").setAttribute("style", "");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost:8080/JSConsole/rest/cars/" + id,
true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var car = JSON.parse(xmlhttp.responseText);
document.getElementById("updName").value = car.name;
document.getElementById("updNameText").innerHTML = car.name;
document.getElementById("updColor").value = car.color;
document.getElementById("updModel").value = car.model;
document.getElementById("updYear").value = car.year;
hideAll();
document.getElementById("sec_update").setAttribute("style", "");
}
};
xmlhttp.send();
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 54
function add() {
hideAll();
document.getElementById("sec_loading").setAttribute("style", "");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://localhost:8080/JSConsole/rest/cars/", true);
xmlhttp.onreadystatechange = function() {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

if (xmlhttp.readyState === 4 && xmlhttp.status === 204) {


showList();
}
};
carObject = {};
carObject.name = document.getElementById("addName").value;
carObject.color = document.getElementById("addColor").value;
carObject.model = document.getElementById("addModel").value;
carObject.year = document.getElementById("addYear").value;
xmlhttp.setRequestHeader("content-type", "application/json");
n s e
xmlhttp.send(JSON.stringify(carObject));
i ce
}
b l el
fer a
function update() {
a n s
tr
var id = document.getElementById("updName").value;
hideAll();
o n -
an
document.getElementById("sec_loading").setAttribute("style", "");
var xmlhttp = new XMLHttpRequest();
h s
a deฺ
xmlhttp.open("PUT", "http://localhost:8080/JSConsole/rest/cars/" + id,
true); )
ฺrs t Gui
s
em uden
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 204) {
showList();
a n @ S t
} s
uk e thi s
}; ฺ v
an s
mil to u
carObject = {};
(
carObject.name = document.getElementById("updName").value;
n
ksa
carObject.color = document.getElementById("updColor").value;

V ucarObject.model = document.getElementById("updModel").value;
carObject.year = document.getElementById("updYear").value;
an
Mil
xmlhttp.setRequestHeader("content-type", "application/json");
xmlhttp.send(JSON.stringify(carObject));
}

function removeCar() {
var id = document.getElementById("updName").value;
hideAll();
document.getElementById("sec_loading").setAttribute("style", "");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("DELETE", "http://localhost:8080/JSConsole/rest/cars/" + id,
true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 204) {
showList();
}
};
xmlhttp.send();
}

function hideAll() {
document.getElementById("sec_add").setAttribute("style", "display:none");
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 55
document.getElementById("sec_list").setAttribute("style", "display:none");
document.getElementById("sec_update").setAttribute("style",
"display:none");
document.getElementById("sec_loading").setAttribute("style",
"display:none");
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

/lesson09/rest/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>REST test</title>
<meta charset="UTF-8">
<script src="code.js"></script>
</head>
n s e
<body>
i ce
<nav>
<ul> b l el
<li><a href="#" onclick="showAdd();">Add a car</a></li>
fer a
<li><a href="#" onclick="showList();">View Cars</a></li>
a n s
</ul>
n - tr
</nav> o
<section id="sec_add">
s an
<h1>Add Car</h1>
) h a deฺ
ฺrs t Gui
<div>
s
name:<input type="text" id="addName">
em uden
color:<input type="text" id="addColor"><br>
@
a n S t
model:<input type="text" id="addModel">
s s
year:<input type="text" id="addYear"><br>
uk e thi
v
<input type="button" value="Add Car" onclick="add();">

</div>
an s
</section>
n (mil to u
<section id="sec_list">

u ksa
<h1>Car List</h1>

n V <div>
a <ul id="carList">
Mil <li><a href="#" >CarName</a></li>
</ul>
</div>
</section>
<section id="sec_update">
<h1>Update Car</h1>
<div>
name:<span id="updNameText"></span><input type="hidden" id="updName">
color:<input type="text" id="updColor"><br>
model:<input type="text" id="updModel">
year:<input type="text" id="updYear"><br>
<input type="button" value="Update Car" onclick="update();">
<input type="button" value="Delete Car" onclick="removeCar();">
</div>
</section>
<section id="sec_loading">
<h1>LOADING...</h1>
</section>
</body>
</html>

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

Appendix JSConsole Examples


Chapter 10 - Page 56
/lesson09/rest/Car.java
public class Car {

private String name;


private String color;
private String model;
private int year;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getColor() { n s e


i ce
el
return color;
}
a b l
fer
public void setColor(String color) {
a n s
}
this.color = color;
n - tr
o
s an
public String getModel() {
) h a deฺ
ฺrs t Gui
return model;
}
s
@ em{ uden
public void setModel(String model)
this.model = model;
a n S t
} s
uk e thi s
ฺ v
i lan to{ us
public int getYear()
m
(
return year;
n
}
ks a
u
an Vpublic void setYear(int year) {
Mil
this.year = year;
}

/lesson09/rest/CarsResource.java
import java.util.HashMap;
import java.util.Map;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 57
import javax.ws.rs.Produces;

@Path("cars")
public class CarsResource {

private static Map<String, Car> cars = new HashMap<>();


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

@GET
@Produces("application/json")
public JsonArray getAll() {
JsonArrayBuilder arrayBld = Json.createArrayBuilder();
for (Car car : cars.values()) {
arrayBld.add(car.getName());
}
return arrayBld.build();
}
n s e
@GET
i ce
@Path("/{carId}")
b l el
@Produces("application/json")
fer a
public JsonObject getRestaurant(@PathParam("carId") String id) {
a n s
-tr
Car car = cars.get(id);
n
JsonObjectBuilder objBld = Json.createObjectBuilder();
o
an
objBld.add("name", car.getName());
objBld.add("color", car.getColor());
objBld.add("model", car.getModel()); h s
a deฺ
)
ฺrs t Gui
objBld.add("year", car.getYear());
s
em uden
return objBld.build();
}
a n @ S t
@POST s
uk e thi s
ฺ v
@Consumes("application/json")
n us
Car car =m i laCar();
public void addReview(JsonObject
t o
content) {

n ( new
a
car.setName(content.getString("name"));
ks
ucar.setModel(content.getString("model"));

an V car.setYear(Integer.parseInt(content.getString("year")));
car.setColor(content.getString("color"));

Mil }
cars.put(car.getName(), car);

@PUT
@Path("/{carId}")
@Consumes("application/json")
public void addReview(@PathParam("carId") String carId, JsonObject content)
{
Car car = cars.get(carId);
car.setModel(content.getString("model"));
car.setColor(content.getString("color"));
car.setYear(Integer.parseInt(content.getString("year")));
}

@DELETE
@Path("/{carId}")
public void deleteReview(@PathParam("carId") String carId) {
cars.remove(carId);
}

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

Appendix JSConsole Examples


Chapter 10 - Page 58
}

WebSocket
WebSocket chat

/lesson09/websocket_chat/code.js
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

var socket = new WebSocket("ws://localhost:8080/JSConsole/chatWebSocket");


socket.onmessage = function(event) {
var chatMessage = event.data;
var messageElement = document.getElementById("messages");
messageElement.innerHTML = "<b>" + chatMessage + "<br>" +
messageElement.innerHTML;
};

function sendMessage() {
var messageField = document.getElementById("message"); n s e
i ce
el
socket.send(messageField.value);
messageField.value = "";
a b l
}
fer
a n s
/lesson09/websocket_chat/index.html
n - tr
o
an
<!DOCTYPE html>
<html>
<head>
h s
a deฺ
)
ฺrs t Gui
<script>parent.window.setDebugConsole();</script>
<title>WebSocket Chat</title> s
<meta charset="UTF-8">
@ em uden
n t
<link rel="stylesheet" href="styles.css">
a S
s
uk e thi
<script src="code.js"></script>
s
</head>
ฺ v
an s
mil to u
<body>
<aside>
n (
<div id="messages"></div>

u ksa
<div id="messageBox">

n V <input type="text" id="message"><input type="button" value="send"


a
Mil
onclick="sendMessage();">
</div>
</aside>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Clients</a></li>
<li><a href="#">Contact Us</a></li>
</ul>
</nav>
<article>
<section>
<p>Text</p>
</section>
</article>
</body>
</html>

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

Appendix JSConsole Examples


Chapter 10 - Page 59
/lesson09/websocket_chat/styles.css
body{
color: #222222;
background: #E3E3E3;
border: 0;
padding: 0;
margin: 0;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

font-family: Arial;
}

article{
float: left;
margin-right: 225px;
background-color: #EFEFEF;

}
nav{ n s e
i ce
}
b l el
aside{
fer a
position: absolute;
a n s
right: 0;
top: 0; n - tr
o
bottom: 0;
s an
width: 220px;
) h a deฺ
ฺrs t Gui
border: 1px solid #555555;
background: #F2F2F2;
s
}
@ em uden
aside #messages{
a n S t
position: absolute; s
uk e thi s
ฺ v
bottom: 30px; ilan
top:0;
u s
left: 0; (m t o
n
right:a0;
} uks

anV
Mil
aside #messageBox{
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 30px;
}

/lesson09/websocket_chat/ChatWebSocket.java
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

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

Appendix JSConsole Examples


Chapter 10 - Page 60
@ServerEndpoint("/chatWebSocket")
public class ChatWebSocket {

private static final Set<Session> sessions = new HashSet<>();


private static final LinkedList<String> messages = new LinkedList<>();
private static int id = 1;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

@OnOpen
public void onOpen(Session session) throws IOException {
sessions.add(session);
session.getUserProperties().put("id", id++);
for (String message : messages) {
session.getBasicRemote().sendText(message);
}
}

@OnMessage
n s e
public void onMessage(Session session, String message) {
i ce
message = "user " + session.getUserProperties().get("id") + " says:\"" +
b l el
message + "\"";
fer a
messages.push(message);
a n s
tr
if (messages.size() > 15) {
messages.pop();
o n -
an
}

Session recipient = iter.next(); h s


for (Iterator<Session> iter = sessions.iterator(); iter.hasNext();) {
a deฺ
try { )
ฺrs t Gui
s
em uden
recipient.getBasicRemote().sendText(message);
} catch (Exception e) {
iter.remove();
a n @ S t
} s
uk e thi s
} ฺ v
an s
mil to u
}

n (
ksa
@OnClose

V u public void onClose(Session session) {


sessions.remove(session);
an
Mil
}
}

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

Appendix JSConsole Examples


Chapter 10 - Page 61
Lesson 10 Developing Applications with jQuery
jQuery
Write jQuery.

/lesson10/jQuery_examples/code.js
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

/* $(document).ready(function() {
// Add code here
}); */
/lesson10/jQuery_examples/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
n s e
<title>The Next Big Front-End Conference</title>
i ce
<meta charset="UTF-8">
b l el
<link rel="stylesheet" href="styles.css" />
<script src="scripts/jquery-1.11.1.js"></script>
fer a
<script src="code.js"></script>
a n s
</head>
n - tr
o
an
<body>
<header>
h s
a deฺ
<h1>The Next Big Conference for Front-End Developers</h1>
<h2>Join us this year</h2> )
ฺrs t Gui
<nav> s
<ul id="main_menu">
@ em uden
n
<li><a href="*">Home</a></li>
a S t
s
uk e thi s
<li><a href="#section-1">Speakers</a></li>
v
<li><a href="#section-2">Workshops</a></li>

an s
<li><a href="#section-3">Submit Proposal</a></li>
</ul>
n
</nav> (mil to u
u ksa
</header>

n V <section id="section-1">
a
Mil
<article>
<header>
<h1>Speakers</h1>
</header>
<p>Text</p>
<p>More Text</p>
<p>Even More Text</p>
<p>Some Text</p>
</article>
</section>
<section id="section-2">
<article>
<header>
<h1>Workshops</h1>
</header>
<p>Text</p>
<p>More Text</p>
<p>Even More Text</p>
<p>Some Text</p>
</article>
</section>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 62
<section id="section-3">
<article>
<header>
<h1>Submit Proposal</h1>
</header>
<p>Text</p>
<p>More Text</p>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<p>Even More Text</p>


<p>Some Text</p>
<form name="proposalForm">
<fieldset>
<p>
<label for="name">Name:(required)</label>
<input type="text" name="name" id="name" required>
</p>
<p>
<label for="email">Email:(required)</label>
n s e
<input type="email" name="email" id="email">
i ce
</p>
b l el
<p><label for="file">Send us a document with the
fer a
abstract:</label></p>
a n s
tr
<input type="file" name="file" id="file">
n -
<p><input type="submit" name="submit" value="submit"></p>
o
an
</fieldset>
</form>
</article> h s
a deฺ
</section> )
ฺrs t Gui
s
em uden
<aside>
<h1>Ads</h1>
a n @ S t
<p class="advertising">UI/UX advertising</p>
</aside> s
uk e thi s
<footer> ฺ v
an s
mil to u
<p class="copyright user-groups">&copy; 2014 Front End User Groups</p>
</footer>
n (
ksa
</body>

V u
</html>

an
Mil /lesson10/jQuery_examples/styles.css

jQuery Events
Handle jQuery events.

/lesson10/jQuery_events/code.js
$(document).ready(function() {
$("#myText").bind("click", function() {
$("#myText").addClass("increased-size");
});

$("#myParagraphs").delegate("p", "mouseover", function() {


$(this).addClass("increased-size");
});

// Uncomment to try the on() method


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

Appendix JSConsole Examples


Chapter 10 - Page 63
/* $("#myText").on("click", function() {
$("#myText").addClass("change-color");
});

$("#myParagraphs").on("mouseover", "p", function()


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

$(this).addClass("change-color");
}); */

// Uncomment to try the trigger() method

// $( "#myText" ).trigger( "click" );

});

/lesson10/jQuery_events/index.html n s e
i ce
<!DOCTYPE html>
<html> b l el
<head>
fer a
<script>parent.window.setDebugConsole();</script>
a n s
<title>jQuery Events</title>
n - tr
<meta charset="UTF-8"> o
<link rel="stylesheet" href="styles.css" />
s an
) h a deฺ
<script src="scripts/jquery-1.11.1.js"></script>

ฺrs t Gui
<script src="code.js"></script>
</head>
s
<body>
@ em uden
<div id="myText">
a n S t
s
Click this text to enlarge it
uk e thi s
</div>
ฺ v
<br/>
an s
n (mil to u
<button onclick="addParagraph()">Add a paragraph</button>
<div id="myParagraphs">

u ksa
</div>

n V <script>
a function addParagraph() {
Mil // create a paragraph element, the variable contains a reference to
the p element
var newParagraphElement = document.createElement("p");
var text = "Pass the mouse over this text to enlarge it";
// create a text node
var newTextElement = document.createTextNode(text);
// insert the newly created text node into the node tree of paragraph
newParagraphElement.appendChild(newTextElement);

document.getElementById("myParagraphs").appendChild(newParagraphElement);
}
</script>
</body>
</html>

/lesson10/jQuery_events/styles.css
.increased-size {
font-size: 300%;
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 64
.change-color {
color: #ff9951;
}
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

jQuery Effects
Create jQuery effects and animation.

/lesson10/jQuery_animation/code.js
$(document).ready(function() {
$("#myText").hide();
$("#myButton").on("click", function() {
$("#myText").show(); n s e
i ce
el
});
$("#myHideButton").on("click", function() {
a b l
$("#myText").hide();
fer
});
a n s
$("#myToggleButton").on("click", function() {
$("#myText").toggle(); n - tr
o
});
s an
$("#mySlideButton").on("click", function() {
) h a deฺ
ฺrs t Gui
$("#myText").slideDown();
});
s
em uden
$("#mySlideHideButton").on("click", function() {
$("#myText").slideUp();
});
a n @ S t
s
uk e thi s
$("#myFadeButton").on("click", function() {
ฺ v
an
$("#myText").fadeIn();
s
mil to u
});
(
$("#myFadeHideButton").on("click", function() {
n
ksa
$("#myText").fadeOut();

V u});

an $("#myChainButton").on("click", function() {

Mil
$("#myText").slideDown().slideUp().fadeIn().fadeOut();
});
$("#myAnimateButton").on("click", function() {
$("#myImg").animate({height: 400, width: 400, opacity: "-=.75"}, 2000);
});
$("#myQueueAnimateButton").on("click", function() {
$("#myImg")
.animate({height: 400}, 1000)
.animate({width: 400}, 1000)
.animate({opacity: "-=.75"}, 1000);
});

$("#myManualQueueAnimateButton").on("click", function() {
$("#myImg").queue(function() {
$(this).animate({height: 400}, 1000);
$(this).dequeue();
});
$("#myImg").queue(function() {
$(this).animate({width: 400}, 1000);
$(this).dequeue();
});
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 65
$("#myImg").queue(function() {
$(this).animate({opacity: "-=.75"}, 1000);
$(this).dequeue();
});
});

$("#myNonQueueAnimateButton").on("click", function() {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("#myImg")
.animate({
height: 400
}, {
duration: 1000,
queue: false,
easing: "linear"
})
.animate({width: 400}, 1000)
.animate({opacity: "-=.75"}, 1000);
n s e
});
i ce
b l el
$("#myStopButton").on("click", function() {
fer a
$("#myImg").stop();
a n s
tr
});

o n -
an
$("#myFinishButton").on("click", function() {
$("#myImg").finish();
}); h s
a deฺ
)
ฺrs {t Gui
s
em u"", nopacity: ""});
$("#myResetButton").on("click", function()
$("#myImg").css({height: "", width:
@ d e
});
a n S t
}); s
uk e thi s
ฺ v
i lan to us
/lesson10/jQuery_animation/index.html
m
n(
<!DOCTYPE html>
<html>sa
V uk
<head>
an <script>parent.window.setDebugConsole();</script>
Mil <title>jQuery Events</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css" />
<script src="scripts/jquery-1.11.1.js"></script>
<script src="code.js"></script>
</head>
<body>
<div id="myButtons">
<button id="myButton" class="buttons">Show</button>
<button id="myHideButton" class="buttons">Hide</button>
<button id="myToggleButton" class="buttons">Toggle</button>
<button id="mySlideButton" class="buttons">Show by Sliding</button>
<button id="mySlideHideButton" class="buttons">Hide by Sliding</button>
<button id="myFadeButton" class="buttons">Show by Fading</button>
<button id="myFadeHideButton" class="buttons">Hide by Fading</button>
<button id="myChainButton" class="buttons">Chain effects</button>
</div>
<div id="myText">
<img src="CSS_small.png" alt="">
<p>Text</p>

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

Appendix JSConsole Examples


Chapter 10 - Page 66
<p>More Text</p>

</div>
<div id="animateButtons">
<button id="myAnimateButton" class="buttons">Animate image</button>
<button id="myQueueAnimateButton" class="buttons">Queued Animate
image</button>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

<button id="myManualQueueAnimateButton" class="buttons">Manual Queued


Animate image</button>
<button id="myNonQueueAnimateButton" class="buttons">Non-
Queued</button>
<button id="myStopButton" class="buttons">Stop</button>
<button id="myFinishButton" class="buttons">Finish</button>
<button id="myResetButton" class="buttons">Reset image</button>
</div>
<img id="myImg" src="JSLogo_small.png" alt="">
</body>
n s e
</html>
i ce
b l el
/lesson10/jQuery_animation/styles.css
fer a
img {
a n s
float: left;
n - tr
} o
s an
#myButtons, #animateButtons {
) h a deฺ
rs t Gui
width: 100px;
float: left;
s ฺ
clear: both;
@ em uden
}
a n S t
s
uk e thi s
.buttons {
ฺ v
n us
width: 90px; ila
height: 65px;

}
n ( m to
u ksa
n V
#animateButtons, #myImg {
a padding: 100px 0px;
Mil }

.resetImg {
height: 100px;
width: 100px;
}

jQuery Ajax
Request data by using jQuery Ajax.

/lesson10/jQuery_ajax/code.js
$(document).ready(function() {
$("#ajaxButton").on("click", function() {
var request = $.ajax({
url: "data/file_1.html",
type: "GET",
dataType: "html"
});
request.done(function(data) {
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 67
$("#content").html(data);
});
});

$("#loadButton").on("click", function() {
$("#content").load("data/file_1.html");
});
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

$("#scriptButton").on("click", function() {
$.getScript("scripts/myscript.js", function() {
console.log("Here some actions after the script is loaded");
});
});

$("#jsonButton").on("click", function() {
$.getJSON("data/list.json", function(data) {
$.each(data, function(key, val) {
n s e
$("#content ul").append("<li id='" + key + "'>" + val + "</li>");
i ce
});
b l el
});
fer a
});
a n s
$("#getButton").on("click", function() {
n - tr
o
an
$.get("data/file_1.html", function(data) {
$("#content").html(data);
}, "html"); h s
a deฺ
}); )
ฺrs t Gui
s
em ude{n
$("#clearButton").on("click", function()
@
$("#content").empty();
a n S t
}); s
uk e thi s
}); ฺ v
m i lan to us
(
/lesson10/jQuery_ajax/scripts/myscript.js
n
ks a
$(document).ready(function() {
V u$("#content").load("data/file_1.html");
an});
Mil /lesson10/jQuery_ajax/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>jQuery Ajax</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css" />
<script src="scripts/jquery-1.11.1.js"></script>
<script src="code.js"></script>
</head>
<body>
<div id="myButtons">
<button id="ajaxButton" class="buttons">ajax() request</button>
<button id="loadButton" class="buttons">load() request</button>
<button id="scriptButton" class="buttons">getScript() request</button>
<button id="jsonButton" class="buttons">getJSON() request</button>
<button id="getButton" class="buttons">get() request</button>
<button id="clearButton" class="buttons">Clear content</button>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.

Appendix JSConsole Examples


Chapter 10 - Page 68
</div>
<div id="content">
<ul>

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

</html>

/lesson10/jQuery_ajax/styles.css
img {
float: left;
}

#myButtons, #animateButtons {
width: 100px;
n s e
float: left;
i ce
}
clear: both;
b l el
fer a
.buttons {
a n s
height: 40px;
n - tr
width: 80px; o
}
s an
) h a deฺ
rs t Gui
#animateButtons, #myImg {
padding: 100px 0px;
s ฺ
}
@ em uden
a n S t
.resetImg {
s
uk e thi s
height: 100px;
ฺ v
}
width: 100px;
m i lan to us
n (
jQuery a
ksUI
u
V some jQuery UI components.
anTry
Mil /lesson10/jQuery_ui/code.js
$(document).ready(function() {
$(function() {
$("#accordion").accordion();
});
});

/lesson10/jQuery_ui/index.html
<!DOCTYPE html>
<html>
<head>
<script>parent.window.setDebugConsole();</script>
<title>jQuery UI</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>
<script src="scripts/jquery-ui-1.11.1.custom/jquery-ui.js"></script>

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

Appendix JSConsole Examples


Chapter 10 - Page 69
<script src="code.js"></script>
</head>
<body>
<div id="accordion">
<h3>Section 1</h3>
<div>
<p>Text</p>
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ

</div>
<h3>Section 2</h3>
<div>
<p>More Text</p>
</div>
<h3>Section 3</h3>
<div>
<p>Even More Text</p>
<ul>
<li>List item one</li>
n s e
<li>List item two</li>
i ce
<li>List item three</li>
b l el
</ul>
fer a
</div>
a n s
tr
</div>
</body>
o n -
an
</html>

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

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

Appendix JSConsole Examples


Chapter 10 - Page 70

You might also like