2. Rise
of
the
Responsive
Single
Page
App
Image:
h6p://johnpolacek.github.io/scrolldeck.js/decks/responsive/
3. Responsive
• Unified
across
experiences
• Can
be
embedded
as
mobile
app
• Be6er
deployment
and
&
maintanence
• Mobile
users
need
to
get
access
to
everything
Image:
h6p://coenraets.org/blog/wp-‐content/uploads/2011/10/directory11.png
4. Single-‐page
ApplicaMons
(SPA)
• Web
app
that
fits
on
a
single
web
page
– Fluid
UX,
like
desktop
app
– Examples
like
Gmail,
Google
maps
• Html
page
contains
mini-‐views
(HTML
Fragments)
that
can
be
loaded
in
the
background
• No
reloading
of
the
page,
be;er
UX
• Requires
handling
of
browser
history,
navigaBon
and
bookmarks
5. JavaScript
• SPAs
are
implemented
using
JavaScript
and
HTML
• ECMAScript
is
a
scripMng
language,
standardized
by
Ecma
InternaMonal
• In
Browsers,
ECMAScript
is
commonly
called
JavaScript
– JavaScript
=
NaBve
(EcmaScript)
+
Host
objects
(browser)
7. JavaScript
• SPAs
are
implemented
using
JavaScript
and
HTML
• ECMAScript
is
a
scripMng
language,
standardized
by
Ecma
InternaMonal
• In
Browsers,
ECMAScript
is
commonly
called
JavaScript
– JavaScript
=
NaBve
(EcmaScript)
+
Host
objects
(browser)
8. Web
Standards?
• Formal
standards
or
technical
specificaBons
that
describe
the
World
Wide
Web
• Web
Standards
consist
of
the
following
– RecommendaMons
of
the
World
Wide
Web
ConsorMum
(W3C)
• (X)HTML,
CSS,
SVG,
DOM
...
– And
also
standards
by
ECMA
InternaBonal
(JavaScript),
Unicode
(Charsets)
and
IANA
(Name
and
number
registries).
9. World
Wide
Web
ConsorMum
• The
World
Wide
Web
ConsorMum
(W3C)
is
the
main
internaMonal
standards
organizaMon
for
the
World
Wide
Web
• CompaBbility
among
industry
members
• W3C
makes
recommenda,ons
for
the
web
• Several
recommendaMons
– XHTML,
DOM,
CSS,
XML...
• URL:
http://www.w3.org/
10. W3C
RecommendaMon:
XHTML
• XHTML™
1.0
The
Extensible
HyperText
Markup
Language
(Second
EdiMon)
– h6p://www.w3.org/TR/xhtml1/
• Markup
language
for
web
pages
• Can
be
used
to
create
structured
documents
by
using
structural
semanMcs
– headings,
paragraph,
lists,
links
...
11. XHTML,
HTML,
HTML5?
SGML:
Standard
Generalized
Markup
Language
Meta
language
XML
Meta
language
(subset
of
SGML)
HTML
(.html)
XHTML
(.xhtml)
MathML
(.mml)
OOXML
(.docx)
12. (X)HTML
versions
• 1996:
HTML
2.0
• 1997:
HTML
3.2
– W3C
RecommendaMon
• 1997:
HTML
4.0
– CSS
• 2000:
XHTML
1.0
– SeparaMon
of
layout
and
the
document
• 2014:
(X)HTML
5
– 2D
drawing,
Offline
storage,
drag
and
drop..
13. W3C
RecommendaMon:
XML
• eXtensible
Markup
Language,
is
a
specificaMon
for
creaMng
custom
markup
languages
• W3C
RecommendaMon
• Primary
purpose
is
to
help
computers
to
share
data
• XML
is
meta-‐language.
This
means
that
you
use
it
for
creaMng
languages.
• XML
is
an
extensive
concept.
14. XML-‐language:
XHTML
<?xml version="1.0"?>!
<!DOCTYPE html !
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"!
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">!
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">!
<head>!
<title>Minimal XHTML 1.0 Document</title>!
</head>!
<body>!
<p>This is a minimal <a href="http://www.w3.org/TR/
xhtml1/">XHTML 1.0</a> !
document.</p>!
</body>!
</html>
17. XML-‐language:
You
can
create
your
own!
<plist version='1.0'>!
<dict>!
<key>Student and Staff Restaurant</key>!
<array>!
<string>Gratinated broccoli</string>!
<string>Oven baked sausage</string>!
<string>Beef in red wine sauce</string>!
<string>Ham and pepperoni baguette</string>!
<string>Baguette with beef roast</string>!
</array>!
<key>Cafeteria</key>!
<array>!
<string>Tomato soup with chevre &</string>!
<string>Ham and pasta salad</string>!
</array>!
</dict>!
</plist>
19. W3C
recommendaMon:
CSS
• Cascading
Style
Sheets
is
used
to
describe
presentaBon
of
a
document
wri6en
in
some
markup
language
– Markup
language
can
be
(x)html
• Different
versions
– CSS
1,
CSS
2,
CSS
3
• Different
browsers
may
support
different
things
in
CSS
20. XHTML
with
CSS
<?xml version="1.0"?>!
<!DOCTYPE html !
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"!
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">!
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"
lang="en">!
<head>!
<title>Minimal XHTML 1.0 Document</title>!
<link rel="stylesheet" href="mystyle.css">!
</head>!
<body>!
<p>This is a minimal <a href="http://www.w3.org/TR/
xhtml1/">XHTML 1.0</a> !
document.</p>!
</body>!
</html> Linking
to
CSS
23. JavaScript,
LiveScript,
JScript,
ECMAScript?
• ScripMng:
add
client-‐side
behaviour
to
the
site
• JavaScript
– Developed
by
Netscape
– Originally
JavaScript,
then
LiveScript
and
then
back
to
JavaScript.
• JScript
– Microsom
made
their
own
version
of
the
JavaScript
• Compa,bility
problems
• =>
ECMAScript,
effort
to
standardize
different
versions
of
the
J(ava)Script
24. ECMAScript
• ECMAScript
is
a
scripMng
language,
standardized
by
Ecma
InternaMonal
• In
Browsers,
ECMAScript
is
commonly
called
JavaScript
– JavaScript
=
NaBve
(EcmaScript)
+
Host
objects
(browser)
• Java/ECMAscript
is
nowdays
heavily
used
with
AJAX
–
based
sites
• SMll
many
problems
because
of
browser
incompaMbilites
25. JavaScript
• EcmaScript
– String,
Number,
Operators,
Statements,
Math,
Date,
Array,
Boolean,
RegExp..
• Browser
BOM
– window,
navigator,
screen,
history,
locaMon
• HTML
DOM
– DOM
document,
element,
a6ribute,
events
• JavaScript
=
EcmaScript
+
BOM
+
DOM
27. JavaScript
• MulM-‐paradigm
scripMng
language
– Support
for
OO
• Can
be
used
in
browsers,
command
line
(rhino,
v8),
server
side
(node
js)
• Easy
to
learn,
hard
to
handle
• Latest
version:
JavaScript
1.8.5,
a
superset
of
ECMAScript
28. In
the
old
days..
• JS
was
designed
to
add
interacMvity
to
HTML
pages
• Dynamic
HTML
• Can
react
to
events:
page
has
finished
loading,
user
clicks..
• Data
validaMon
• Browser
detecMon
• Cookies
29. …
then
came
AJAX
• JavaScript
is
heavily
used
in
AJAX-‐based
sites
• AJAX:
asynchronous
JavaScript
and
XML
– group
of
interrelated
techniques
used
on
the
client-‐side
to
create
rich
web
apps
where
data
is
retrieved
from
the
server
in
the
background.
• Example
usage:
Gmail,
Google
Maps
30. Today!
• Mobile
ApplicaMons
• Windows
8
applicaMons
• Desktop
widgets
• Server
side
JS
34. Word
about
Tools
• Code
editor
is
good
enough
– Notepad++,
Sublime
Text
• Also
IDEs
available
– WebStorm
• Browsers
hold
JS
console
and
debugging
tools
• To
print
to
console
– console.log("hello world!");
37. Variables
• Values
are
stored
in
variables
• Variables
are
declared:
– var carname;
• Assigning
value
– carname = "volvo";
• Together
– var carname = "volvo";
38. Basic
Types
• JavaScript
is
loosely
typed
language!
• Basic
types
– Numbers
floaMng
point
number
(64
bit)
– Strings
(16
bit
UNICODE)
– Booleans
(true,
false)
– null
(value
that
isn’t
anything)
– undefined
(undefined
value)
– Objects
(all
the
rest)
39. AutomaMc
type
conversion
5 + null // returns 5 because null is converted to 0!
"5" + null // returns "5null" because null is converted to "null"!
"5" + 1 // returns "51" because 1 is converted to "1" !
"5" - 1 // returns 4 because "5" is converted to 5
40. string
• Series
of
characters
• Indexes
zero
based,
first
char
0,
second
1
• Examples
– var mj1 = "hello";
– var mj2 = "hello "world"";
• Methods
available
– charAt(), replace(), split()
• See:
http://www.w3schools.com/js/
js_strings.asp
41. array
• Arrays
are
an
list
like
objects
• Indexes
0,
1
…
• Can
grow
at
runMme
• Example
– var arr = ['hello', 'world'];!
– console.log(arr[0]);!
– console.log(arr.length);
47. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"!
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">!
<html xmlns="http://www.w3.org/1999/xhtml">!
<head>!
<title>Embed Example</title>!
<meta http-equiv="content-type" content="application/xhtml+xml;
charset=utf-8" />!
<script type="text/javascript">!
//<![CDATA[!
function askQuestion()!
{!
var name = prompt("Please enter your name","Harry Potter");!
!
if ( name != "" )!
{!
alert("Hello " + name + "! How are you today?");!
}!
}!
!
//]]>!
</script>!
</head>!
<body>!
!<input type="button" onclick="askQuestion();" value="Question for me" />!
!
</body>!
</html>
50. Control
Structures
• Control
Structures
works
as
expected
• if,
while,
do
while,
for
etc.
51. Comparison
(w3schools)
<script type="text/javascript">!
//<![CDATA[!
!
var d = new Date();!
var time = d.getHours();!
!
if ( time < 10 )!
{!
document.write("<b>Good morning</b>");!
}!
!
//]]>!
</script>
52. Comparison
(w3schools)
<script type="text/javascript">!
//<![CDATA[!
!
var d = new Date();!
var time = d.getHours();!
!
if ( time < 10 )!
{!
document.write("<b>Good morning</b>");!
}!
else!
{!
document.write("<b>Good Day</b>"); !
}!
//]]>!
</script>
53. Repeat
(w3schools)
<script type="text/javascript">!
//<![CDATA[!
!
var i=0;!
while (i<=5)!
{!
document.write("The number is " + i);!
document.write("<br />");!
i = i + 1;!
}!
!
//]]>!
</script>
54. About
for
in
• For
in
iterates
enumerable
properMes
of
an
object
in
arbitrary
order!
• Example
– for(variable in object) { … }
• You
can
iterate
also
array,
but
remember
that
order
is
not
guaranteed
57. Variable
scope
• Global
and
local
variables
• JS
does
not
have
block
statement
scope!
function test() {
if(true) {
var x = 5;
}
document.write(x);
}
• This
works!
X
is
defined
in
the
scope
of
the
funcMon
(or
globally)
58. HoisMng
• Variables
are
moved
on
top
of
the
funcMon!
function test() { !
var x;!
if(true) {!
x = 5;!
}!
document.write(x);!
}
59. Global
Objects
• Global
variables
are
in
fact
properMes
of
the
global
object!
•
In
web
pages
the
global
object
is
window
• So
– var
x
=
5
ó
window.x
=
5;
65. JS
and
Objects
• JS
can
adopt
some
OOP
concepts
• Developer
can
– Define
and
instanMate
an
object
using
new
– Declare
an
object
on
the
fly
– Extend
an
object
• JS
makes
automaMc
conversions
from
data-‐
types
to
objects
(for
example:
string)
66. Object
Literal
var mystring = “hello!”;!
var myarray = [“element1”, “element2”];!
var myboolean = true;!
var circle1 = {radius: 9, getArea :
someFunction };!
var circle2 = {!
radius: 9,!
getRadius: function() {!
return this.radius;!
}!
}
67. No
Classes!
• One
of
the
simplest
way
to
create
object
– var
obj
=
new
Object();
– obj.x
=
10;
– obj.y
=
12;
• This
adds
dynamically
two
properMes
to
the
obj
–
object!
• Object
is
built
–
in
data
type
• Objects
are
key
value
pairs!
68. “Class”
• To
define
a
class,
define
a
funcMon
function Foo() {
this.x = 1;
this.y = 1;
}
• var obj = new Foo();
• // Internally a Object is created
69. Example
function Circle(radius) {!
this.radius = radius;!
this.getArea = function() {!
return (this.radius * this.radius) * Math.PI;!
};!
}!
!
var myobj = new Circle(5);!
document.write(myobj.getArea());
81. Intro
to
Events
• Some
interacMon
on
html
–
page:
– Mouse
click
(onclick)
– Web
page
loading
(onload)
– Mousing
over
and
out
(onmouseover
onmouseout)
– Submiyng
HTML
form
(onsubmit)
– Key
handling,
web
page
compleMng,
user
scrolling
or
resizing
…
82. EvoluMon
of
Events
• DOM
Level
0
(Introduced
in
Netscape)
– <a
href="h6p://www.opera.com/"
onclick="alert('Hello')">Say
hello</a>
• DOM
Level
2
(W3C)
– document.getElementById("my-‐
link").addEventListener("click",
myFuncMon,
false);
• Microsom
(IE)
did
not
follow
the
W3C
model
unMl
IE8.
IE11
deletes
its
support
for
MS
model
88. W3C
DOM
• DOM
–
Document
Object
Model
–
cross-‐
pla}orm
and
language-‐independent
convenMon
for
interacMng
with
objects
in
HTML
and
in
XML.
• With
DOM
you
can
manipulate
html/xml
document!
Dynamic
html!
• Public
interface
available:
h6p://www.w3.org/
DOM/DOMTR
89. W3C
DOM
Levels
• (
DOM
Level
0
and
Intermediate
DOM
)
– Not
W3C
Standards,
used
in
Netscape
2
(Level
0)
and
Netscape
4
(Intermediate
DOM)
• DOM
Level
1
– 1998:
Ability
to
change
enMre
HTML
or
XML
document
• DOM
Level
2
– 2001:
Introduces
“getElementById”
funcMon,
event
model
and
support
for
XML
namespaces
• DOM
Level
3
– 2004:
XPath,
keyboard
event
handling
• Support
varies!
– h6p://www.webbrowsercompaMbility.com/dom/desktop/
90. DOM
Level
2
Event
Handling
• Methods
for
adding
and
removing
events
– addEventListener
– removeEventListener
• MulMple
event
handlers
can
be
registered
for
the
same
event!
91. Node
• In
DOM,
each
object
is
Node
• In
this
– <p>Hello</p>
• You
have
two
nodes
1)
element
node
p
2)
text
node
Hello
• Text
node
is
child
node
of
p
element.
P
element
is
parent
node
of
the
text
node
92. Node
Example
<p>This is a <strong>paragraph</strong></p>!
<p>
|
--------------
| |
This is a <strong>
|
|
paragraph
97. Access
var title =
document.firstChild.firstChild.lastChild;!
// document.html.head.title!
!
var title =
document.firstChild.childNodes[0].childNodes[0];
98. Geyng
Element
Easier
Way
var x = document.getElementsByTagName('strong')[0]!
!
var x = document.getElementById('hereweare');
99. Changing
the
Node
// <a href="" id="someId">Link</p>!
var x = document.getElementById('someId');!
x.firstChild.nodeValue = "Hello!";!
x.setAttribute("href", "http:/…");
100. Inner
HTML
// <a href="" id="someId">Link</p>!
var x = document.getElementById("someId");!
x.innerHTML = "Hello!";!
!
// innerHTML is NOT W3C Standard and it’s!
// slower…
101. CreaMng
and
Removing
Nodes
var x = document.createElement('hr');!
document.getElementById('inserthrhere').appendChild(x);!
!
var node = document.getElementById('inserthrhere')!
node.removeChild(node.childNodes[0]);!
!
var x = document.createTextNode('SomeText');!
document.getElementById('hereweare').appendChild(x);
102. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"!
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">!
<html xmlns="http://www.w3.org/1999/xhtml">!
<head>!
<title></title>!
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />!
<script type="text/javascript">!
//<![CDATA[!
function change()!
{!
// Get list of ALL <h1> - elements!
var listOfHeading1 = window.document.getElementsByTagName("h1"); !
// Find the first <h1> - element in the list!
var heading1 = listOfHeading1[0];!
// Get the child - element of the first <h1> - element (Text)!
var text = heading1.firstChild;!
// Replace the text!
text.data = "Hello from JS!"; !
}!
//]]>!
</script>!
</head>!
<body>!
!<
h1>Title</h1>!
<input type="button" onClick="change();" value="click!"/>!
</body>!
</html>
103. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"!
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">!
<html xmlns="http://www.w3.org/1999/xhtml">!
<head>!
<title></title>!
<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />!
<script type="text/javascript">!
//<![CDATA[!
function change()!
{!
// Reference to the table - element!
var table = document.getElementById("mytable"); !
var tr = document.createElement("tr"); // <tr>!
var td1 = document.createElement("td"); // <td>!
var td1Text = document.createTextNode("New Cell"); // "New Cell" !
td1.appendChild(td1Text); // <td>New Cell</td>!
!
var td2 = document.createElement("td"); // <td>!
var td2Text = document.createTextNode("New Cell"); // "New Cell"!
td2.appendChild(td2Text); // <td>New Cell</td>!
!
tr.appendChild(td1); !
tr.appendChild(td2);!
table.appendChild(tr);!
}!
!
//]]>!
</script>!
!
</head>!
<body>!
!<
table id="mytable" border="1">!
<tr><td> </td><td> </td></tr>!
<tr><td> </td><td> </td></tr>!
<tr><td> </td><td> </td></tr>!
</table>!
!<
input type="submit" onClick="change();" value="Add Row"/>!
!
</body>!
</html>
105. AJAX
• Asynchronous
JavaScript
and
XML
• AJAX
is
about
updaMng
parts
of
web
page
without
reloading
the
whole
page
• Google
Maps,
Gmail
• EssenMal
part
when
creaMng
SPA
apps!
107. XMLH6pRequest
• Modern
browsers
support
built-‐in
XMLH;pRequest
object
• All
about
sending
and
receiving
data
from
server.
• InstanMate
in
normal
fashion:
– var xmlobj = new XMLHttpRequest();
108. Send
Request
to
Server
var xmlobj = new XMLHttpRequest();!
!
xmlobj.open("GET", // POST or GET? !
"somefile.txt", // URL!
true); // async or not?!
!
xmlobj.send(); // Send it
109. Using
POST
var xmlobj = new XMLHttpRequest();!
!
xmlobj.open("POST", // POST or GET? !
"somescript.php", // URL!
true); // async or not?!
!
// Specify the data you want to send via POST!
xmlobj.setRequestHeader("Content-type","application/
x-www-form-urlencoded");!
!
// Send data!
xmlobj.send("name=Kalle");
110. Asynchronous?
• When
seyng
the
async
parameter
to
true,
the
server
side
script
is
run
in
background.
• Javascript
does
not
have
to
wait
for
the
server
response..
You
can
– Execute
other
scripts
while
waiMng
server
response
– Deal
with
the
response
when
ready
• Specify
a
funcBon
that
is
called
when
response
is
ready!
111. <script type="text/javascript">!
var xmlobj;!
function retrieveFromServer() {!
xmlobj = new XMLHttpRequest();!
!
xmlobj.onreadystatechange = changesHappening;!
!
xmlobj.open("GET", // POST or GET? !
"somefile.txt", // URL!
true); // async or not?!
!
xmlobj.send(); // Send it!
}!
!
function changesHappening() {!
var myarray = new Array("UNSENT",!
"OPENED",!
"HEADERS RECEIVED",!
"LOADING",!
"DONE");!
!
alert(myarray[xmlobj.readyState]);!
}!
</script>!
!
</head>!
!<
body>!
<p>!
<button type="button" onclick="retrieveFromServer()">Change Content</button>!
</p>!
!
<p id="here"></p>
112. State
of
the
Request
• 0:
Not
iniMalized
• 1:
Server
connecMon
established
• 2:
Request
received
• 3:
Processing
request
• 4:
Request
Finished
and
Response
Ready
113. <script type="text/javascript">!
var xmlobj;!
!
function retrieveFromServer() {!
xmlobj = new XMLHttpRequest();!
!
xmlobj.onreadystatechange = changesHappening;!
!
xmlobj.open("GET", // POST or GET? !
"somefile.txt", // URL!
true); // async or not?!
!
xmlobj.send(); // Send it!
!
}!
!
function changesHappening() {!
if (xmlobj.readyState == 4) {!
document.getElementById("text").innerHTML = xmlobj.responseText;!
}!
}!
</script>!
!
</head>!
!
<body>!
!
<p>!
<button type="button" onclick="retrieveFromServer()">Change Content</button>!
</p>
114. Status
of
the
Request
• Also
HTTP
Status
is
received
– 200:
“Ok”
– 404:
“Page
not
found”
– …
• if(xmlobj.status == 200 &&
xmlobj.readyState == 4) { .. }
115. Server
Response
• XMLH6pRequest
has
two
a6ributes
for
the
response
– DOMString responseText
– Document responseXML
116. Parsing
XML
function changesHappening() {!
! if (xmlobj.readyState == 4) {!
! var xmlDoc = xmlobj.responseXML;!
! var titles = xmlDoc.getElementsByTagName("Title");!
!
! var result = "";!
!
! for (i = 0; i < titles.length; i++) {!
! result = result +
titles[i].childNodes[0].nodeValue + "<br />";!
! }!
!
! document.getElementById("text").innerHTML = result;!
! }!
!}
117. Working
in
Local
Environment
• If
you
get
"cross
origin
requests
are
only
supported
for
HTTP"
..
• Either
– 1)
Disable
web
security
in
your
browser
– 2)
Use
some
web
server
and
access
files
h6p://..
• To
disable
web
security
in
Chrome
/
Windows
– taskkill /F /IM chrome.exe
– "C:Program Files (x86)GoogleChromeApplication
chrome.exe" --disable-web-security --allow-file-access-from-
files
118. Simple
Server
using
Node.js
• Install
Node.js
and
– npm install connect serve-static
• Amer
that
create
server.js
file:
– var connect = require('connect');
– var serveStatic = require('serve-static');
– connect().use(serveStatic(__dirname)).listen(8080);
• Run
– node server.js
• Open
– http://localhost:8080/index.html
120. HTML
• Very
simple
way
to
do
AJAX
• Server
has
fragments
of
HTML
• No
parsing
or
converMng
• Easy
to
update
UI:
use
can
use
innerHTML
or
standard
DOM
121. XML
• StaMc
XML
Data
on
server
or
generated
XML
• XML
must
be
parsed:
use
DOM
scripMng
• Example
of
PHP
-‐>
XML
-‐>
AJAX
122. Example
function showResponse(req) {
// if the request is ready
if (req.readyState == 4 && req.status ==
200) {
var data = req.responseXML;
// here we have to process XML data
}
}
}
123. JSON
• JavaScript
Object
NotaMon
• Storing
and
exchanging
text
• Smaller
than
XML,
faster
and
easier
to
parse!
• Language
Independent
125. Parsing
JSON
in
JS
• You
can
convert
JSON
text
to
Object
using
eval
–
funcMon:
– var myObject = eval(‘(‘ + JSONText + ‘)’);
• You
should
NOT
use
eval
for
security
issues!
Eval
executes
also
any
js
program…
• Use
JSON
Parses
instead!
It
recognizes
only
JSON
text
126. Example
(wikipedia)
var my_JSON_object = {};!
var http_request = new XMLHttpRequest();!
http_request.open("GET", url, true);!
http_request.onreadystatechange = function () {!
var done = 4, ok = 200;!
if (http_request.readyState == done && http_request.status == ok) {!
my_JSON_object = JSON.parse(http_request.responseText);!
my_JSON_object.weathertoday;!
}!
};!
http_request.send(null);
129. JQuery?
• MoMvaMon
– Simple
things
may
require
lot
of
coding
– Common
browsers
are
different
and
implementaMon
varies
• SoluMon,
use
a
framework
– jQuery
is
a
fast
and
concise
JavaScript
Library
that
simplifies
HTML
document
traversing,
event
handling,
animaMng,
and
Ajax
interacMons
for
rapid
web
development.
130. How?
• Download
JQuery
file
– http://jquery.com/download/
• Make
your
HTML5
page
and
reference
to
the
file
in
script
block
• Make
your
code
and
use
JQuery
funcMons!
131. <script type="text/javascript" src="jquery.js"></script>!
!
<script type="text/javascript">!
!
// When document is ready to be manipulated!
jQuery(document).ready( pageReadyToBeManipulated );!
!
function pageReadyToBeManipulated() {!
// If link is clicked!
jQuery("a").click( linkClick );!
}!
!
function linkClick(event) {!
alert("Thanks for visiting!");!
// Prevent the default action!
event.preventDefault(); !
}!
!
</script>
132. Some
Basic
Syntax
• JQuery
can
be
used
in
two
ways:
– JQuery()
– Or
– $()
• $
is
an
alias
to
JQuery()!
$
more
commonly
used
133. <script type="text/javascript" src="jquery.js"></script>!
!
<script type="text/javascript">!
//<![CDATA[!
!
// When document is ready to be manipulated!
$(document).ready( pageReadyToBeManipulated );!
!
function pageReadyToBeManipulated() {!
// If link is clicked!
$("a").click( linkClick );!
}!
!
function linkClick(event) {!
alert("Thanks for visiting!");!
// Prevent the default action!
event.preventDefault(); !
}!
!
//]]>!
</script>
134. // USING ANONYMOUS FUNCTIONS and document - obj is not!
// needed..!
<script type="text/javascript" src="jquery.js"></script>!
!
<script type="text/javascript">!
//<![CDATA[!
!
$().ready(function(){!
$("a").click(function(event){!
alert("Thanks for visiting!");!
event.preventDefault();!
});!
});!
!
//]]>!
</script>
135. Ge6ers
in
the
TradiMonal
Way
• getElementsById
• getElementsByTagName
• getAttribute
136. JQuery
and
Selectors
• Select
all
h1
elements
– $("h1")
• Select
the
first
one
– $("h1")[0]
• Add
contents
– $("h1")[0].innerHTML = "hello!";
• Lot
of
different
selectors
– http://api.jquery.com/category/selectors/
137. CreaMng
Elements
in
TradiMonal
Way
• createElement
• createTextNode
• setAttribute
• appendChild
• removeChild
138. JQuery
Insert
$().ready(function(){!
$("a").click(function(event){!
!
// Insert the new element after element with id here!
$("<p>New Element</p>").insertAfter("#here");!
!
event.preventDefault();!
});!
});
142. Angular
JS
• Single
Page
App
Framework
for
JavaScript
• Implements
client-‐side
Model-‐View-‐Whatever
pa6ern
– Some
call
it
MVC,
some
MVVM,
it
does
not
ma6er:
– SeparaBon
of
presentaMon
from
business
logic
and
presentaBon
state
• No
direct
DOM
manipulaMon,
less
code
• Support
for
all
major
browsers
• Supported
by
Google
• Large
and
fast
growing
community
143. First
Example
–
Template
<!DOCTYPE html>!
<html ng-app>!
<head>!
DirecMve
<title>!
Title!
</title>!
<meta charset="UTF-8" />!
<style media="screen"></style>!
<script src="angular.min.js"></script>!
</head>!
<body>!
<!-- initialize the app -->!
<div>!
Download
this
file
from:
https://angularjs.org/
DirecMve
<!-- store the value of input field into a variable name -->!
<p>Name: <input type="text" ng-model="name"></p>!
<!-- display the variable name inside (innerHTML) of p -->!
<p ng-bind="name"></p>!
</div>!
</body>!
</html>
Template
144. Basic
Concepts
• 1)
Templates
– HTML
with
addiMonal
markup,
direcMves,
expressions,
filters
...
• 2)
DirecBves
– Extend
HTML
using
ng-app,
ng-bind,
ng-model
• 3)
Filters
– Filter
the
output:
filter,
orderBy,
uppercase
• 4)
Data
Binding
– Bind
model
to
view
using
expressions
{{ }}
145. 2)
DirecMves
• DirecBves
apply
special
behavior
to
a6ributes
or
elements
in
HTML
– A6ach
behaviour,
transform
the
DOM
• Some
direcMves
– ng-app
• IniMalizes
the
app
– ng-model
• Stores/updates
the
value
of
the
input
field
into
a
variable
– ng-bind
• Replace
the
text
content
of
the
specified
HTML
with
the
value
of
given
expression
146. About
Naming
• AngularJS
HTML
Compiler
supports
mulMple
formats
– ng-bind
• Recommended
Format
– data-ng-bind
• Recommended
Format
to
support
HTML
validaMon
– ng_bind, ng:bind, x-ng-bind
• Legacy,
don't
use
147. Lot
of
Built
in
DirecMves
• ngApp
• ngClick
• ngController
• ngModel
• ngRepeat
• ngSubmit
• ngDblClick
• ngMouseEnter
• ngMouseMove
• ngMouseLeave
• ngKeyDown
• ngForm
148. 2)
Expressions
• Angular
expressions
are
JavaScript-‐like
code
snippets
that
are
usually
placed
in
bindings
– {{ expression }}.
• Valid
Expressions
– {{ 1 + 2 }}
– {{ a + b }}
– {{ items[index] }}
• Control
flow
(loops,
if)
are
not
supported!
• You
can
use
filters
to
format
or
filter
data
152. 3)
Filter
• With
filter,
you
can
format
or
filter
the
output
• Formajng
– currency, number, date, lowercase,
uppercase
• Filtering
– filter, limitTo
• Other
– orderBy, json
158. HTML5
• Fimh
version
of
HTML
standard
by
W3C
• Simple
markup
that
can
be
wri6en
either
in
HTML
or
XHTML
syntax
• PotenMal
candidate
for
cross
plakorm
mobile
apps
160. APIs
• APIs
and
DOM
is
fundamental
part
of
the
specificaMon
• APIs
– Offline
Web
apps
– Drag
and
drop
– GeolocaMon
– Web
SQL
database
– …
161. Example:
GeolocaMon
API
• GeolocaMon
API
SpecificaMon
– h6p://dev.w3.org/geo/api/spec-‐source.html
• To
detect
the
locaMon
of
the
client
• In
mobile:
GPS,
in
desktop
IP-‐address
or
Wi-‐Fi
locaMon
162. function setText(val, e) {!
document.getElementById(e).value = val;!
}!
!
function insertText(val, e) {!
document.getElementById(e).value += val;!
}!
!
var nav = null; !
!
function requestPosition() {!
if (nav == null) {!
nav = window.navigator;!
}!
if (nav != null) {!
var geoloc = nav.geolocation;!
if (geoloc != null) {!
geoloc.getCurrentPosition(successCallback);!
}!
else {!
alert("geolocation not supported");!
}!
}!
else {!
alert("Navigator not found");!
}!
}!
!
function successCallback(position)!
{!
alert("" + position.coords.latitude + ", " + position.coords.longitude);!
}
165. Canvas
• “The
canvas
element
a
resolu,on-‐dependent
bitmap
canvas,
which
can
be
used
for
dynamically
rendering
of
images
such
as
game
graphics,
graphs,
or
other
images”
• Image
is
drawn
in
JavaScript
using
typical
vector
graphics
drawing
primiMves
– drawImage(),
lineTo(),
arcTo(),
bezierCurveTo(),
fillRect(),
scale(),
rotate(),
translate(),
createLinearGradient(),
shadowBlur(),
…
166. Simple
Drawing
using
Canvas
and
JS
<canvas id="mycanvas" width="200" height="200" />!
!
<script>!
var canvas= document.getElementById('mycanvas');!
var context = canvas.getContext('2d');!
context.fillRect(60,30,80,120);!
</script>