WEB TODAY
Rise of the Responsive Single Page App Image: h6p://johnpolacek.github.io/scrolldeck.js/decks/responsive/
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
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
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)
INTRO TO WEB STANDARDS
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)
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).
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/
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 ...
XHTML, HTML, HTML5? SGML: Standard Generalized Markup Language Meta language XML Meta language (subset of SGML) HTML (.html) XHTML (.xhtml) MathML (.mml) OOXML (.docx)
(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..
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.
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>
XML-­‐language: SVG <?xml version="1.0"?>! <!DOCTYPE svg ! PUBLIC "-//W3C//DTD SVG 1.1//EN" ! "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">! <svg width="100%" height="100%" version="1.1"! xmlns="http://www.w3.org/2000/svg">! !< circle cx="100" cy="50" r="40" stroke="black"! stroke-width="2" fill="red"/>! ! </svg>
XML-­‐language: MathML <?xml version="1.0"?>! <!DOCTYPE math:math PUBLIC "-//OpenOffice.org//DTD Modified W3C MathML 1.01//EN" "math.dtd">! <math:math xmlns:math="http://www.w3.org/1998/Math/MathML">! <math:semantics>! <math:mrow>! <math:mi>x</math:mi>! <math:mo math:stretchy="false">=</math:mo>! <math:mfrac>! <math:mrow>! ...! </math:mrow>! <math:annotation math:encoding="StarMath 5.0">x = {-b +- sqrt{b^{2}-4{ac}} } over {2 {a}} </math:annotation>! </math:semantics>! </math:math>!
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 &amp;</string>! <string>Ham and pasta salad</string>! </array>! </dict>! </plist>
HTML5: It's really easy! <!DOCTYPE html>! <html>! <head>! <title>! Title! </title>! ! <meta charset="UTF-8" />! <style media="screen"></style>! <script></script>! </head>! ! <body>! The content! </body>! </html>
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
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
CSS: mystyle.css p {! font-family: Arial, serif;! color: RGB(255,0,0);! }
Result in Browser
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
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
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
INTRODUCTION TO JAVASCRIPT
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
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
… 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
Today! • Mobile ApplicaMons • Windows 8 applicaMons • Desktop widgets • Server side JS
QUICK EXAMPLE OF JS
<!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" />! </head>! <body>! !< p>! !< script type="text/javascript">! //<![CDATA[! // Embed JS! document.write("Hello from JS!");! ! //]]>! </script>! ! </p>! ! </body>! </html>
<!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" />! </head>! <body>! !< p>! ! // External JS! <script type="text/javascript" src="test.js">! </script>! ! </p>! ! </body>! </html>
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!");
EXERCISE 1
INTRO TO PROGRAMMING WITH JS
Variables • Values are stored in variables • Variables are declared: – var carname; • Assigning value – carname = "volvo"; • Together – var carname = "volvo";
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)
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
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
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);
...! <body>! !< p>! <script type="text/javascript">! //<![CDATA[! ! // Declaration! var car;! // Assigning! car = "Volvo";! document.write(car);! ! //]]>! </script>! </p>! ! </body>! </html>
Input & Output using Dialogs • Alert Box – alert("some text"); • Prompt Box – prompt("sometext", "default value")
<!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" />! </head>! <body>! !< input type="button" onclick="alert('moi');" value="Show alert box" />! ! </body>! </html>
Result
<!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 showAlert()! {! alert("Hello World!");! }! //]]>! </script>! </head>! <body>! !< input type="button" onclick="showAlert();" value="Show alert box" />! ! </body>! </html>
<!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>
EXERCISE 2 + 3
CONTROL STRUCTURES
Control Structures • Control Structures works as expected • if, while, do while, for etc.
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>
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>
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>
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
EXERCISE 4
JS FUNCTIONS
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)
HoisMng • Variables are moved on top of the funcMon! function test() { ! var x;! if(true) {! x = 5;! }! document.write(x);! }
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;
Basic FuncMon function add(a, b) ! { ! return a + b;! } ! alert(add(1,2));
FuncMon as Variable var add = function(a, b) ! { ! return a+b;! } ! alert(add(1,2));
FuncMon as Variable var add = function theAdd(a, b) ! { ! return a+b;! } ! alert(add(1,2)); // produces 3! alert(theAdd(1,2)); // also produces 3
EXERCISE 5
OBJECTS IN JS
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)
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;! }! }
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!
“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
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());
EXERCISE 6
JS BOM AND EVENTS
JavaScript • JavaScript = ECMAScript + Host Objects • In Browsers, host objects are – BOM (Browser object model) – DOM (Document object model)
Browser Object Model • Mostly BOM is about – Handling windows – Handling browser properMes – Cookies
Objects DOM BOM Image: h6p://www.daaq.net/old/javascript/index.php?page=the+js+bom
window's methods
navigator
screen
locaMon
history
EVENTS: DOM LEVEL 0
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 …
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
Events
Canceling Default Behaviour • You may cancel some events: – <a href="http://www.tamk.fi/" onclick="alert('message'); return false;">
<!DOCTYPE html>! <html>! <head>! <title>! Title! </title>! <meta charset="UTF-8" />! <style media="screen"></style>! <script>! function count()! {! var height = document.forms.myform.height.value;! var weight = document.forms.myform.weight.value;! document.forms.myform.result.value = (weight / (height*height));! }! </script>! </head>! <body>! <form name="myform">! Height (m):<br/>! <input type="text" name="height"/><br/>! Weight (kg):<br/>! <input type="text" name="weight"/><br/>! <input type="button" onclick="count();" value="BMI"/><br/>! BMI<br/>! <input type="text" name="result"/>! </form>! </body>! </html>
EXERCISE 7
DOM
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
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/
DOM Level 2 Event Handling • Methods for adding and removing events – addEventListener – removeEventListener • MulMple event handlers can be registered for the same event!
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
Node Example <p>This is a <strong>paragraph</strong></p>! <p> | -------------- | | This is a <strong> | | paragraph
A6ribute Node <a href="http://www.tamk.fi">TAMK</a> <a> ----------------- | | TAMK href | http://www.tamk.fi
Nodes • Element node: p, img, a • Text node: sometext • A6ribute node: src
DOM Level 1: To Access DOM tree • X can be some node – var parent = x.parentNode; – var firstchild = x.childNodes[0]; • How to get reference to x?
Document object
Access var title = document.firstChild.firstChild.lastChild;! // document.html.head.title! ! var title = document.firstChild.childNodes[0].childNodes[0];
Geyng Element Easier Way var x = document.getElementsByTagName('strong')[0]! ! var x = document.getElementById('hereweare');
Changing the Node // <a href="" id="someId">Link</p>! var x = document.getElementById('someId');! x.firstChild.nodeValue = "Hello!";! x.setAttribute("href", "http:/…");
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…
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);
<!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>
<!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>&nbsp;</td><td>&nbsp;</td></tr>! <tr><td>&nbsp;</td><td>&nbsp;</td></tr>! <tr><td>&nbsp;</td><td>&nbsp;</td></tr>! </table>! !< input type="submit" onClick="change();" value="Add Row"/>! ! </body>! </html>
AJAX
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!
How AJAX works? (W3schools)
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();
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
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");
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!
<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>
State of the Request • 0: Not iniMalized • 1: Server connecMon established • 2: Request received • 3: Processing request • 4: Request Finished and Response Ready
<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>
Status of the Request • Also HTTP Status is received – 200: “Ok” – 404: “Page not found” – … • if(xmlobj.status == 200 && xmlobj.readyState == 4) { .. }
Server Response • XMLH6pRequest has two a6ributes for the response – DOMString responseText – Document responseXML
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;! ! }! !}
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
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
DATA FORMATS
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
XML • StaMc XML Data on server or generated XML • XML must be parsed: use DOM scripMng • Example of PHP -­‐> XML -­‐> AJAX
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 } } }
JSON • JavaScript Object NotaMon • Storing and exchanging text • Smaller than XML, faster and easier to parse! • Language Independent
Example { "employees": [ { "firstName": "John", "lastName" : "Doe" }, { "firstName": "Anna", "lastName" : "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }
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
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);
Example …! "location" : { "city" : "San Francisco",! "country" : "US",! "country_iso3166" : "US",! "country_name" : "USA",! "l" : "/q/zmw:94101.1.99999",! "lat" : "37.77500916",! "lon" : "-122.41825867",! "magic" : "1",! "nearby_weather_stations" : { "airport" : { "station" : [ { "city" : "San Francisco",! …! ! var myObject = JSON.parse(httpReq.responseText);! var city = myObject.location.city;
INTRO TO JQUERY AND ANGULARJS
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.
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!
<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>
Some Basic Syntax • JQuery can be used in two ways: – JQuery() – Or – $() • $ is an alias to JQuery()! $ more commonly used
<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>
// 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>
Ge6ers in the TradiMonal Way • getElementsById • getElementsByTagName • getAttribute
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/
CreaMng Elements in TradiMonal Way • createElement • createTextNode • setAttribute • appendChild • removeChild
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();! });! });
ManipulaMon FuncMons • .addClass() • .amer() • .append() • .css() • … • See: h6p://api.jquery.com/category/ manipulaMon/
Example $("#show").click(function(event) {! $("#here").show("slow");! event.preventDefault();! });
ANGULARJS
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
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
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 {{ }}
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
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
Lot of Built in DirecMves • ngApp • ngClick • ngController • ngModel • ngRepeat • ngSubmit • ngDblClick • ngMouseEnter • ngMouseMove • ngMouseLeave • ngKeyDown • ngForm
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
Example <!DOCTYPE html>! <html ng-app>! <head>! <title>Title</title>! <meta charset="UTF-8" />! <style media="screen"></style>! <script src="../angular.min.js"></script>! </head>! <body>! <div>! DirecMve DirecMve <p>Number 1: <input type="number" ng-model="number1"></p>! <p>Number 2: <input type="number" ng-model="number2"></p>! <!-- expression -->! <p>{{ number1 + number2 }}</p>! </div>! </body>! </html> Expression
Valid HTML5 version <!DOCTYPE html>! <html data-ng-app="">! <head>! <title>Title</title>! Add data-­‐ <meta charset="UTF-8" />! <style media="screen"></style>! <script src="../angular.min.js"></script>! </head>! <body>! <div>! Add data-­‐ <p>Number 1: <input type="number" data-ng-model="number1"></p>! <p>Number 2: <input type="number" data-ng-model="number2"></p>! <!-- expression -->! <p>{{ number1 + number2 }}</p>! </div>! </body>! </html>
ng-­‐init and ng-­‐repeat direcMves <html data-ng-app="">! <head>! <title>Title</title>! <meta charset="UTF-8" />! <script src="../angular.min.js" type="text/javascript">! </script>! </head>! !< body>! <div data-ng-init="names = ['Jack', 'John', 'Tina']">! <h1>Cool loop!</h1>! <ul>! <li data-ng-repeat="name in names">{{ name }}</li>! </ul>! </div>! </body>! </html>
3) Filter • With filter, you can format or filter the output • Formajng – currency, number, date, lowercase, uppercase • Filtering – filter, limitTo • Other – orderBy, json
Using Filters -­‐ Example <!DOCTYPE html>! <html data-ng-app="">! <head>! ! <title>Title</title>! <meta charset="UTF-8">! <script src="../angular.min.js" type="text/javascript">! </script>! </head>! !< body>! <div data-ng-init="customers = [{name:'jack'}, {name:'tina'}]">! <h1>Cool loop!</h1>! <ul>! <li data-ng-repeat="customer in customers | orderBy:'name'">! {{ customer.name | uppercase }}</li>! </ul>! </div>! </body>! </html> Filter Filter
Using Filters -­‐ Example <!DOCTYPE html>! !< html data-ng-app="">! <head>! <title>Title</title>! <meta charset="UTF-8">! <script src="../angular.min.js" type="text/javascript">! </script>! </head>! <body>! <div data-ng-init=! "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]">! <h1>Customers</h1>! ! <ul>! <li data-ng-repeat="customer in customers | orderBy:'name' | filter:'john'">{{! customer.name | uppercase }}</li>! </ul>! </div>! </body>! </html>
Using Filters – User Input Filters the Data <!DOCTYPE html>! !< html data-ng-app="">! <head>! <title>Title</title>! <meta charset="UTF-8">! <script src="../angular.min.js" type="text/javascript">! </script>! </head>! <body>! <div data-ng-init=! "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]">! <h1>Customers</h1>! ! <input type="text" data-ng-model="userInput" />! <ul>! <li data-ng-repeat="customer in customers | orderBy:'name' | filter:userInput">{{! customer.name | uppercase }}</li>! </ul>! </div>! </body>! </html>
EXERCISE 10
HTML5
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
New Syntax • <video> • <audio> • <canvas> • <secMon>, <arMcle>, <header>, <nav>
APIs • APIs and DOM is fundamental part of the specificaMon • APIs – Offline Web apps – Drag and drop – GeolocaMon – Web SQL database – …
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
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);! }
Mobile App (iPhone) Web app!
Mobile App (iPhone)
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(), …
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>
PossibiliMes • Simple shapes (Rectangles) • Complex shapes (Paths) • Lines • Shadows • Text • Images • Pixel manipulaMon • Colors and styles • ComposiMng • TransformaMons • Canvas state
Example: ImplemenMng a Game
EXERCISE 11

Introduction to JavaScript

  • 1.
  • 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)
  • 6.
    INTRO TO WEB STANDARDS
  • 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 <?xmlversion="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>
  • 15.
    XML-­‐language: SVG <?xmlversion="1.0"?>! <!DOCTYPE svg ! PUBLIC "-//W3C//DTD SVG 1.1//EN" ! "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">! <svg width="100%" height="100%" version="1.1"! xmlns="http://www.w3.org/2000/svg">! !< circle cx="100" cy="50" r="40" stroke="black"! stroke-width="2" fill="red"/>! ! </svg>
  • 16.
    XML-­‐language: MathML <?xmlversion="1.0"?>! <!DOCTYPE math:math PUBLIC "-//OpenOffice.org//DTD Modified W3C MathML 1.01//EN" "math.dtd">! <math:math xmlns:math="http://www.w3.org/1998/Math/MathML">! <math:semantics>! <math:mrow>! <math:mi>x</math:mi>! <math:mo math:stretchy="false">=</math:mo>! <math:mfrac>! <math:mrow>! ...! </math:mrow>! <math:annotation math:encoding="StarMath 5.0">x = {-b +- sqrt{b^{2}-4{ac}} } over {2 {a}} </math:annotation>! </math:semantics>! </math:math>!
  • 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 &amp;</string>! <string>Ham and pasta salad</string>! </array>! </dict>! </plist>
  • 18.
    HTML5: It's really easy! <!DOCTYPE html>! <html>! <head>! <title>! Title! </title>! ! <meta charset="UTF-8" />! <style media="screen"></style>! <script></script>! </head>! ! <body>! The content! </body>! </html>
  • 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
  • 21.
    CSS: mystyle.css p{! font-family: Arial, serif;! color: RGB(255,0,0);! }
  • 22.
  • 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
  • 26.
  • 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
  • 31.
  • 32.
    <!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" />! </head>! <body>! !< p>! !< script type="text/javascript">! //<![CDATA[! // Embed JS! document.write("Hello from JS!");! ! //]]>! </script>! ! </p>! ! </body>! </html>
  • 33.
    <!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" />! </head>! <body>! !< p>! ! // External JS! <script type="text/javascript" src="test.js">! </script>! ! </p>! ! </body>! </html>
  • 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!");
  • 35.
  • 36.
  • 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);
  • 42.
    ...! <body>! !< p>! <script type="text/javascript">! //<![CDATA[! ! // Declaration! var car;! // Assigning! car = "Volvo";! document.write(car);! ! //]]>! </script>! </p>! ! </body>! </html>
  • 43.
    Input & Output using Dialogs • Alert Box – alert("some text"); • Prompt Box – prompt("sometext", "default value")
  • 44.
    <!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" />! </head>! <body>! !< input type="button" onclick="alert('moi');" value="Show alert box" />! ! </body>! </html>
  • 45.
  • 46.
    <!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 showAlert()! {! alert("Hello World!");! }! //]]>! </script>! </head>! <body>! !< input type="button" onclick="showAlert();" value="Show alert box" />! ! </body>! </html>
  • 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>
  • 48.
  • 49.
  • 50.
    Control Structures •Control Structures works as expected • if, while, do while, for etc.
  • 51.
    Comparison (w3schools) <scripttype="text/javascript">! //<![CDATA[! ! var d = new Date();! var time = d.getHours();! ! if ( time < 10 )! {! document.write("<b>Good morning</b>");! }! ! //]]>! </script>
  • 52.
    Comparison (w3schools) <scripttype="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) <scripttype="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
  • 55.
  • 56.
  • 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;
  • 60.
    Basic FuncMon functionadd(a, b) ! { ! return a + b;! } ! alert(add(1,2));
  • 61.
    FuncMon as Variable var add = function(a, b) ! { ! return a+b;! } ! alert(add(1,2));
  • 62.
    FuncMon as Variable var add = function theAdd(a, b) ! { ! return a+b;! } ! alert(add(1,2)); // produces 3! alert(theAdd(1,2)); // also produces 3
  • 63.
  • 64.
  • 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 varmystring = “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());
  • 70.
  • 71.
    JS BOM AND EVENTS
  • 72.
    JavaScript • JavaScript = ECMAScript + Host Objects • In Browsers, host objects are – BOM (Browser object model) – DOM (Document object model)
  • 73.
    Browser Object Model • Mostly BOM is about – Handling windows – Handling browser properMes – Cookies
  • 74.
    Objects DOM BOM Image: h6p://www.daaq.net/old/javascript/index.php?page=the+js+bom
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 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
  • 83.
  • 84.
    Canceling Default Behaviour • You may cancel some events: – <a href="http://www.tamk.fi/" onclick="alert('message'); return false;">
  • 85.
    <!DOCTYPE html>! <html>! <head>! <title>! Title! </title>! <meta charset="UTF-8" />! <style media="screen"></style>! <script>! function count()! {! var height = document.forms.myform.height.value;! var weight = document.forms.myform.weight.value;! document.forms.myform.result.value = (weight / (height*height));! }! </script>! </head>! <body>! <form name="myform">! Height (m):<br/>! <input type="text" name="height"/><br/>! Weight (kg):<br/>! <input type="text" name="weight"/><br/>! <input type="button" onclick="count();" value="BMI"/><br/>! BMI<br/>! <input type="text" name="result"/>! </form>! </body>! </html>
  • 86.
  • 87.
  • 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>Thisis a <strong>paragraph</strong></p>! <p> | -------------- | | This is a <strong> | | paragraph
  • 93.
    A6ribute Node <ahref="http://www.tamk.fi">TAMK</a> <a> ----------------- | | TAMK href | http://www.tamk.fi
  • 94.
    Nodes • Element node: p, img, a • Text node: sometext • A6ribute node: src
  • 95.
    DOM Level 1: To Access DOM tree • X can be some node – var parent = x.parentNode; – var firstchild = x.childNodes[0]; • How to get reference to x?
  • 96.
  • 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>&nbsp;</td><td>&nbsp;</td></tr>! <tr><td>&nbsp;</td><td>&nbsp;</td></tr>! <tr><td>&nbsp;</td><td>&nbsp;</td></tr>! </table>! !< input type="submit" onClick="change();" value="Add Row"/>! ! </body>! </html>
  • 104.
  • 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!
  • 106.
    How AJAX works? (W3schools)
  • 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 varxmlobj = 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">! varxmlobj;! 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">! varxmlobj;! ! 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 functionchangesHappening() {! ! 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
  • 119.
  • 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
  • 124.
    Example { "employees":[ { "firstName": "John", "lastName" : "Doe" }, { "firstName": "Anna", "lastName" : "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] }
  • 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) varmy_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);
  • 127.
    Example …! "location": { "city" : "San Francisco",! "country" : "US",! "country_iso3166" : "US",! "country_name" : "USA",! "l" : "/q/zmw:94101.1.99999",! "lat" : "37.77500916",! "lon" : "-122.41825867",! "magic" : "1",! "nearby_weather_stations" : { "airport" : { "station" : [ { "city" : "San Francisco",! …! ! var myObject = JSON.parse(httpReq.responseText);! var city = myObject.location.city;
  • 128.
    INTRO TO JQUERY AND ANGULARJS
  • 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 ANONYMOUSFUNCTIONS 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();! });! });
  • 139.
    ManipulaMon FuncMons •.addClass() • .amer() • .append() • .css() • … • See: h6p://api.jquery.com/category/ manipulaMon/
  • 140.
    Example $("#show").click(function(event) {! $("#here").show("slow");! event.preventDefault();! });
  • 141.
  • 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
  • 149.
    Example <!DOCTYPE html>! <html ng-app>! <head>! <title>Title</title>! <meta charset="UTF-8" />! <style media="screen"></style>! <script src="../angular.min.js"></script>! </head>! <body>! <div>! DirecMve DirecMve <p>Number 1: <input type="number" ng-model="number1"></p>! <p>Number 2: <input type="number" ng-model="number2"></p>! <!-- expression -->! <p>{{ number1 + number2 }}</p>! </div>! </body>! </html> Expression
  • 150.
    Valid HTML5 version <!DOCTYPE html>! <html data-ng-app="">! <head>! <title>Title</title>! Add data-­‐ <meta charset="UTF-8" />! <style media="screen"></style>! <script src="../angular.min.js"></script>! </head>! <body>! <div>! Add data-­‐ <p>Number 1: <input type="number" data-ng-model="number1"></p>! <p>Number 2: <input type="number" data-ng-model="number2"></p>! <!-- expression -->! <p>{{ number1 + number2 }}</p>! </div>! </body>! </html>
  • 151.
    ng-­‐init and ng-­‐repeat direcMves <html data-ng-app="">! <head>! <title>Title</title>! <meta charset="UTF-8" />! <script src="../angular.min.js" type="text/javascript">! </script>! </head>! !< body>! <div data-ng-init="names = ['Jack', 'John', 'Tina']">! <h1>Cool loop!</h1>! <ul>! <li data-ng-repeat="name in names">{{ name }}</li>! </ul>! </div>! </body>! </html>
  • 152.
    3) Filter •With filter, you can format or filter the output • Formajng – currency, number, date, lowercase, uppercase • Filtering – filter, limitTo • Other – orderBy, json
  • 153.
    Using Filters -­‐ Example <!DOCTYPE html>! <html data-ng-app="">! <head>! ! <title>Title</title>! <meta charset="UTF-8">! <script src="../angular.min.js" type="text/javascript">! </script>! </head>! !< body>! <div data-ng-init="customers = [{name:'jack'}, {name:'tina'}]">! <h1>Cool loop!</h1>! <ul>! <li data-ng-repeat="customer in customers | orderBy:'name'">! {{ customer.name | uppercase }}</li>! </ul>! </div>! </body>! </html> Filter Filter
  • 154.
    Using Filters -­‐ Example <!DOCTYPE html>! !< html data-ng-app="">! <head>! <title>Title</title>! <meta charset="UTF-8">! <script src="../angular.min.js" type="text/javascript">! </script>! </head>! <body>! <div data-ng-init=! "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]">! <h1>Customers</h1>! ! <ul>! <li data-ng-repeat="customer in customers | orderBy:'name' | filter:'john'">{{! customer.name | uppercase }}</li>! </ul>! </div>! </body>! </html>
  • 155.
    Using Filters – User Input Filters the Data <!DOCTYPE html>! !< html data-ng-app="">! <head>! <title>Title</title>! <meta charset="UTF-8">! <script src="../angular.min.js" type="text/javascript">! </script>! </head>! <body>! <div data-ng-init=! "customers = [{name:'jack'}, {name:'tina'}, {name:'john'}, {name:'donald'}]">! <h1>Customers</h1>! ! <input type="text" data-ng-model="userInput" />! <ul>! <li data-ng-repeat="customer in customers | orderBy:'name' | filter:userInput">{{! customer.name | uppercase }}</li>! </ul>! </div>! </body>! </html>
  • 156.
  • 157.
  • 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
  • 159.
    New Syntax •<video> • <audio> • <canvas> • <secMon>, <arMcle>, <header>, <nav>
  • 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);! }
  • 163.
  • 164.
  • 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>
  • 167.
    PossibiliMes • Simple shapes (Rectangles) • Complex shapes (Paths) • Lines • Shadows • Text • Images • Pixel manipulaMon • Colors and styles • ComposiMng • TransformaMons • Canvas state
  • 168.
  • 169.