JS&HTML5 - Develop web application_ag
JS&HTML5 - Develop web application_ag
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
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.
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:
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ฺ
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.
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
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
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
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
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
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
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
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.
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
Assumptions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ
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.
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.
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.
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.
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
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.
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
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
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
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:
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
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
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
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
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
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
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
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
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
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
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
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
<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/>
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.
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
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.
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);
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
You can check the solved version of the code.js file in the following folder:
/home/oracle/labs/solutions/lab_05_01
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
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
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));
}
}
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
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
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
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.
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 {
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");
Assumption
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ
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
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
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) {
listContainer.appendChild(taskNode);
save();
}
function removeTask(task) {
var listContainer = document.getElementById("toDoList");
}
}
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
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
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
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
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
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:
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:
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
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
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
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.
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">
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
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.
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.
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
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.
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.
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.
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;.
ukCalculate
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.
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
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
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
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
n (m t
After you
ks a
have finished, your application should look similar to the following:
u
anV
Mil
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
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
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.
};
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:
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
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
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
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
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"}
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
<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
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++) {
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
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
/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);
i
var course = {name:
m lan"JavaScript",
t o u s students: 5, frequency: "daily"};
(
s an
console.log("course
k
object => " + course);
function Courses() {
}
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));
console.log("**Special Operators**");
// Special Operators
for (var i = 0, j = 9; i <= 9; i++, j--)
console.log(i + " , " + j);
/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"
};
Objects
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ
/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 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
waterProof: true
}
};
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 = {
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);
// iterating arrays
// prints all the elements in the array, including undefined
for (var i = 0; i < c.length; i += 1) {
console.log(c[i]);
}
console.log("**Multi-dimensional Arrays**");
// Multi-dimensional Arrays
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
var tic_tac_toe = [
[0, 0, 'X'],
['X', 0, 'X'],
['X', 0, 0]
];
an Vvar result = x * y;
Mil
return result;
};
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.
Tree.prototype.getType = function() {
return this.type;
};
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ
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.
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
/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>
</aside>
<footer>
<p>© 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>
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.
<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>© 2014 Front End User Groups</p>
an
Mil
</footer>
</body>
</html>
/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.
</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.
/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.
<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>© 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;
/**
* 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 *
* @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.
<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.
<p>UI/UX advertising</p>
</aside>
<footer>
<p>© 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);
function removeText() {
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ
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() {
/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>
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
/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
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);
/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.
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"> </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 = {};
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.
/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.
//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ฺ
//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.
/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"> </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.
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
/lesson06/jsonEx/code.js
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ
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;";
}
<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.
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
/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.
.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.
<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;
}
/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>
/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ฺ
/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>
/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("**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.
/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);
/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.
outer();
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.
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.
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());
/lesson08/dnd/code.js
function drag(event) {
event.dataTransfer.setData("Text", "Dragged");
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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.
/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.
/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ฺ
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>
/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.
/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";
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>
/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.
/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);
});
/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
/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>
/lesson09/rest/code.js
window.addEventListener("load", function() {
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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.
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.
/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>
/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.
@Path("cars")
public class CarsResource {
@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);
}
WebSocket
WebSocket chat
/lesson09/websocket_chat/code.js
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2018, Oracle and/or its affiliatesฺ
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">
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;
@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
}
n (
ksa
@OnClose
/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.
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");
});
$(this).addClass("change-color");
}); */
});
/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.
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.
$("#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>
</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ฺ
}
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.
$("#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.
</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>
</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