32
HR360 – HTML5 Preparation (Mini) Guide 25.02.2013 Mario Delgado Picazo

Html5

Embed Size (px)

Citation preview

Page 1: Html5

HR360 – HTML5 Preparation (Mini)

Guide25.02.2013

Mario Delgado Picazo

Page 2: Html5

AGENDA

1. Syllabus2. Semantic Structure3. CSS3 Selectors and Style Properties4. Advanced layout and animation5. Javascript Core Capabilities6. DOM Interactions7. Advanced Topics8. Other topics9. JQuery

Page 3: Html5

1 Syllabus

Test information: http://www.microsoft.com/learning/en/us/exam.aspx?id=70-480

Implement and Manipulate Document Structures and Objects (24%)• Create the document structure.• Write code that interacts with UI controls.• Apply styling to HTML elements programmatically.• Implement HTML5 APIs.• Establish the scope of objects and variables.• Create and implement objects and methods.

Implement Program Flow (25%)• Implement program flow.• Raise and handle an event.• Implement exception handling.• Implement a callback.• Create a web worker process.

Access and Secure Data (26%)• Validate user input by using HTML5 elements.• Validate user input by using JavaScript.• Consume data.• Serialize, deserialize, and transmit data.

Use CSS3 in Applications (25%)• Style HTML text properties.• Style HTML box properties.• Create a flexible content layout.• Create an animated and adaptive UI.• Find elements by using CSS selectors and jQuery.• Structure a CSS file by using CSS selectors.

Page 4: Html5

2 Semantic Structure• Structure

Tag Description<article> Defines an article<aside> Defines content aside from the page content

<bdi> Isolates a part of text that might be formatted in a different direction from other text outside it

<command> Defines a command button that a user can invoke

<details> Defines additional details that the user can view or hide

<summary> Defines a visible heading for a <details> element

<figure> Specifies self-contained content, like illustrations, diagrams, photos, code listings, etc.

<figcaption> Defines a caption for a <figure> element<footer> Defines a footer for a document or section<header> Defines a header for a document or section

<hgroup> Groups a set of <h1> to <h6> elements when a heading has multiple levels

<mark> Defines marked/highlighted text

<meter> Defines a scalar measurement within a known range (a gauge)

<nav> Defines navigation links<progress> Represents the progress of a task

<rp> Defines what to show in browsers that do not support ruby annotations

<section> Defines a section in a document<time> Defines a date/time

Page 5: Html5

2 Semantic Structure

• Input types

<input type="text" name="myname">

<input type="password" name="mypassword">

<input type="url" name="myurl" placeholder=”http://www.google.com” required=”required”>

<input type="email" name="myemail" placeholder=”[email protected]”>

<input type="number" name="mynumber" min="1" max="5">

<datalist id="browsers"><option value="Internet Explorer"><option value="Firefox">

</datalist>

Page 6: Html5

3 CSS3 Selectors and Style Properties

• Media tags

Tag Description<audio> Defines sound content<video> Defines a video or movie

<source>Defines multiple media resources for <video> and <audio>

<embed>Defines a container for an external application or interactive content (a plug-in)

<track> Defines text tracks for <video> and <audio>

<audio controls autoplay loop preload="auto"><source src="horse.ogg" type="audio/ogg"><source src="horse.mp3" type="audio/mpeg">

Your browser does not support the audio element.</audio>or<audio src="horse.ogg" controls autoplay loop preload="auto"></audio>

<video autoplay loop muted width="320" height="240" controls preload=”node”>

<source src="movie.mp4" type="video/mp4"><source src="movie.ogg" type="video/ogg">

Your browser does not support the video tag.</video>or<video src="movie.ogg" controls>Your browser does not support the video tag.</video>

Page 7: Html5

3 CSS3 Selectors and Style Properties• Canvas vs. SVG

Canvas• Resolution dependent• No support for event handlers• Poor text rendering capabilities• You can save the resulting image as .png or .jpg• Well suited for graphic-intensive games

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">Your browser does not support this Canvas!</canvas><script>var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.fillStyle="#FF0000";ctx.fillRect(0,0,150,75);</script>

SVG• Resolution independent• Support for event handlers• Best suited for applications with large rendering

areas (Google Maps)• Slow rendering if complex• Not suited for game applications

<svg width="200" height="200"><rect fill=rgb(0,0,255) x="10" y="10" width="180" height="180"></svg><svg height="200"><polygon points="100,10 40,180 190,60 10,60 160,180"style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;"></svg>

Page 8: Html5

3 CSS3 Selectors and Style Properties• Selectors

Selector Example Example description.class .intro Selects all elements with class="intro"#id #firstname Selects the element with id="firstname"* * Selects all elementselement p Selects all <p> elementselement,element div,p Selects all <div> elements and all <p> elementselement element div p Selects all <p> elements inside <div> elementselement>element div>p Selects all <p> elements where the parent is a <div> elementelement+element div+p Selects all <p> elements that are placed immediately after <div> elements[attribute] [target] Selects all elements with a target attribute[attribute=value] [target=_blank] Selects all elements with target="_blank"[attribute~=value] [title~=flower] Selects all elements with a title attribute containing the word "flower"[attribute|=value] [lang|=en] Selects all elements with a lang attribute value starting with "en":link a:link Selects all unvisited links:visited a:visited Selects all visited links:active a:active Selects the active link:hover a:hover Selects links on mouse over:focus input:focus Selects the input element which has focus:first-letter p:first-letter Selects the first letter of every <p> element:first-line p:first-line Selects the first line of every <p> element:first-child p:first-child Selects every <p> element that is the first child of its parent:before p:before Insert content before the content of every <p> element:after p:after Insert content after every <p> element:lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with "it"element1~element2 p~ul Selects every <ul> element that are preceded by a <p> element[attribute^=value] a[src^="https"] Selects every <a> element whose src attribute value begins with "https"

Page 9: Html5

3 CSS3 Selectors and Style Properties• Selectors (II)

Selector Example Example description[attribute$=value] a[src$=".pdf"] Selects every <a> element whose src attribute value ends with ".pdf"[attribute*=value] a[src*="w3schools"] Selects every <a> element whose src attribute value contains the substring "w3schools":first-of-type p:first-of-type Selects every <p> element that is the first <p> element of its parent:last-of-type p:last-of-type Selects every <p> element that is the last <p> element of its parent:only-of-type p:only-of-type Selects every <p> element that is the only <p> element of its parent:only-child p:only-child Selects every <p> element that is the only child of its parent:nth-child(n) p:nth-child(2) Selects every <p> element that is the second child of its parent:nth-last-child(n) p:nth-last-child(2) Selects every <p> element that is the second child of its parent, counting from the last child:nth-of-type(n) p:nth-of-type(2) Selects every <p> element that is the second <p> element of its parent:nth-last-of-type(n) p:nth-last-of-type(2) Selects every <p> element that is the second <p> element of its parent, counting from the last child:last-child p:last-child Selects every <p> element that is the last child of its parent:root :root Selects the document’s root element:empty p:empty Selects every <p> element that has no children (including text nodes):target #news:target Selects the current active #news element (clicked on a URL containing that anchor name):enabled input:enabled Selects every enabled <input> element:disabled input:disabled Selects every disabled <input> element:checked input:checked Selects every checked <input> element:not(selector) :not(p) Selects every element that is not a <p> element::selection ::selection Selects the portion of an element that is selected by a user

Page 10: Html5

3 CSS3 Selectors and Style Properties• Color properties• named color• hex (#)• rgb()/rgba()• hsl()/hsla()

• Basic text properties• text-decoration: overline/underline/line-through• text-transform: nome/lowercase/uppercase/capitalize• text-shadow (i.e., 2px 2px gray)

Page 11: Html5

3 CSS3 Selectors and Style Properties• Font properties

• font-style: normal/italic/oblique• font-variant: normal/small-caps• font-weight: normal/bold/bolder/light/lighter/#• font-size: {length}• line-height: {length}• font-family: {font}• font shorthand property

• Defining a font

@font-face {font-family: “niftyfont”;src: url(“/type/nifty_n.woff”) format(woff)

}

Page 12: Html5

3 CSS3 Selectors and Style Properties• Box properties• Visibility

• display (inline/block/inline-block/none/...)• visibility (visible/hidden)• white-space (normal/pre/nowrap/pre-wrap/pre-line)• overflow (visible/hidden/scroll/auto)

display:none hides an element, and it will not take up any space.visibility:hidden hides an element, but it will still take up the same space as before.

• Other• box-shadow (i.e., 10px 10px 5px #888888)• borderradius (i.e., 5px)• linear-gradient (i.e., background-image: linear-gradient(to right, black 0%, white 100%))• radial-gradient (i.e., background-image: radial-gradient(circle at 50% 50%, black 0%,

white100%))

Page 13: Html5

4 Advanced layout and animation

• Positioning

Tag Description

static Default. Elements render in order, as they appear in the document flow

absolute The element is positioned relative to its first positioned (not static) ancestor element

fixed The element is positioned relative to the browser window

relative The element is positioned relative to its normal position, so "left:20" adds 20 pixels to the element's LEFT position

inherit The value of the position property is inherited from the parent element

Page 14: Html5

4 Advanced layout and animation

• DisplayTag Descriptionnone The element will not be displayed at allbox (or flex-box) The element is displayed as a block-level flex container boxblock The element is displayed as a block-level element (like paragraphs and headers)flex The element is displayed as a block-level flex container boxinline This is default. The element is displayed as an inline-level element (like span)

inline-block The element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element

inline-flex The element is displayed as an inline-level flex container boxinline-table The element is displayed as an inline-level table

list-item The element is displayed as a list-item, which means that it has a bullet in front of it

table The element is displayed as a tabletable-caption The element is displayed as a table captiontable-cell The element is displayed as a table celltable-column The element is displayed as a table columntable-column-group The element is displayed as a table column group (like <colgroup>)table-footer-group The element is displayed as a table footer row grouptable-header-group The element is displayed as a table header row grouptable-row The element is displayed as a table rowtable-row-group The element is displayed as a table row groupinherit The value of the display property will be inherited from the parent element

Page 15: Html5

4 Advanced layout and animation

• Flexbox• display: -ms-flexbox lays its childrem out horizontally. Its a simple solution to a very common scenario.• horizontal Flexboxes has a good inflience over the layout of their children• -ms-flex-pack: distribute: alignment of the child item of long the access of layout (distribution along the

space equally; like columns centered, like the example of horizontal)• -ms-flex-pack: start | end | center | justify

• start: Initial value. Flexbox items are packed toward the start of the line.• end: Flexbox items are packed toward the end of the line.• center: Flexbox items are packed toward the center of the line.• justify: Flexbox items are evenly distributed in the line.

• -ms-flex: 1 0 auto: is for the children. The first number indicates the positive flexibility, the second is the recomended size.

• -ms-flex-wrap: wrap:• -ms-flex-wrap: none | wrap | wrap-reverse

• none: All child elements are displayed in a single row or column.• wrap: Child elements are wrapped and displayed in successive, parallel rows or

• columns. The object expands in height or width. It's similar to my grid, but better.• wrap-reverse: Child elements are

Page 16: Html5

4 Advanced layout and animation

• Grid• power of tables but implemented in CSS• absolute rows and columns• spanning• Alignment

• Question: if I put -ms-grid-column: 100px 1fr 2fr 100px we will have 4 columns, the first and the last will have 100px, and the third will be the double of the second. Each fr (fractions) are flexible. Ex: 100px 1fr 100px

• The key difference between Flexbox and Grid is that Flexbox lays out its content along a single axis (vertical or horizontal) whereas grid can lay out content in both rows and columns. And flexboxes are flow and grids have structures.

Page 17: Html5

4 Advanced layout and animation• rotate: rotation in clock sense, in grades. Can be rotate, rotateX, rotateY and rotateZ. Ex: transform:rotate(20deg);

• skew: Can be screwX, screwZ and screwY. Ex: transform:skewX(20deg);• scale: Can be scaleX, scaleY and scaleZ also. Increases or reduce the size. Ex: transform:scale(1.5,1.5);

• translate: moving. translate(x,y) Can be also translateX, translateY and translateZ. Ex: translate(10,5)• Animations

We create an animation:@keyframes test_animation {

0% {color: black;}30% {color: blue;}70% {color: purple;}100% {color: red;}

}

And then we can set the class of the anymation:.animation-test-animation {

animation: test_animation 5s fordwards;}

Creates an animation of 5 seconds, changing the color each %.

Page 18: Html5

5 Javascript Core Capabilities

• Variables• Types: strings, number, boolean, array, object, null, undefined.

• Functions• Callable behaviors, implemented as objects.

• function f1(){ } → f3(f1())...• var f2 = function () { }; → f3(f2)...

• By default, there is “arguments” (as a keyword) declared, despite the function has not arguments. It is an array, and you can put in the function as argument whatever you want.

• You can define functions inside functions. Ex:function outerFunction(n) {

function innerFunction() {return n * n;

}return innerFunction();

}var x = outerFunction(4); //innerFunction cannot be called directly

Page 19: Html5

5 Javascript Core Capabilities

• ArraysVar fruit = ['orange', 'apfel', 'pear'];• fruit.sort(); -> returns an array sorted.• fruit.push('pear'); -> put it in the end, not in a copy of the array.• fruit.pop(); -> return an delete the first element (FIFO)• fruit.concat(vegetables) -> Concat the array given, in a copy of the array.• fruit.slice(0, 1) -> gives a sub-array, like substring. From-to function.• fruit.splice(0, 1(, [...])) -> like slice, but 1 is the number of elements taken. Can add otherselements, but it is not mandatory.• fruit,map(function(i) {return i.toUpperCase()}); -> Apply a function to all the elements,returning the new array. Can also change the type, for example, with “.length”.• Fruit.filter(function(i) { return (i.length>5); }); -> delete all the elements with length <= 5.• Fruit.every(function(i) { return (i.length>5); }); -> returns a boolean, if every elements haslength > 5.• Fruit.some(function(i) { return (i.length>5); }); -> like every, but some.

Page 20: Html5

5 Javascript Core Capabilities

• Objectsvar dog = {};dog.breed = “German Shepherd”;dog.bark = function() { alert('Guau!'); }var dog = {

breed : “German Shepherd”,bark : function() { alert('Guau!')

}var dog = {

“breed” : “German Shepherd”,“bark” : function() { alert('Guau!')

}

JSON syntax: the double commas are mandatory and cannot add functions:{“breed” : “German Shepherd”}

function auto(aBrand, aModel, aColor) { this.brand = aBrand; this.model = aModel; this.color = aColor; this.selectBrand = function selectBrand(otherBrand){ this.brand = otherBrand }; this.selectModel = function selectModel(otherModel){ this.model = otherModel }; this.howItIs = function howItIs(){ return "Brand: " + this.brand + "<br />" + "Model: " + this.model + "<br />" + "Color: " + this.color; };}

<script>var firstCar = new auto("Volkswagen", "Golf", "Rojo");document.getElementById("div1").innerHTML = firstCar.howItIs();</script>

Page 21: Html5

6 DOM Interactions

• Queries in DOM• getElementById• getElementsByName• getElementsByTagName: returns a NodeList of all a elements with a specified name.• getElementsByClassName• querySelector: returns the first element found of the type given.• querySelectorAll: returns a NodeList of all a elements of the type given.

• Manipulating the DOM• We can:

• add / modify / remove

• change style → object.className = “newClass” or object.className.add(“newClass”)• We can, in a container, container.appendChild, container.removeChild and as a parameters,

document.createItem(<<type>>).

Page 22: Html5

6 DOM Interactions

• Events:• Ex. NOT RECOMMENDED:

function sayHello() { alert('Hello'); }

<button id=”myButton” onclick="sayHello()">Say Hello</button>

• Ex. RECOMMENDED:function sayHello() { alert('Hello'); }var b = document.querySelector('#myButton');b.addEventListener(“click”, sayHello); or b.onclick = sayHello/null/function(){...}

<button id=”myButton”>Say Hello</button>

Page 23: Html5

7 Advanced Topics

• Handling exceptions• Minimizing failures in code• Managing failures in codetry {

//line of suspicious code} catch(err) {

//mamaging the error: description of the error} finally {

//success or failure, code executes here}

• To throw an error: var err = New Error(123, “Error in helper”);throw err;//orthrow new WinJS.ErrorFromName(“Args”, “There is an error in the args.”);

• WinJS.ErrorFromName and throw are the two ways in which you can throw an error.

Page 24: Html5

7 Advanced Topics

• Promises (necessary WinRTM):• In Windows 8 apps, if a function needs more than 50ms in the execution, it must be

asyncronous.• Every calls to WinJS returns a WinJS.Promise object. Then we have to handle this object.

• To create a Promise:var myPromise = new WinJS.Promise(function(c, e, p) {try{

longTaskAsyncPromise().then(function(){ c(); });} catch (err){

e(err);}});

• c → “completed” function• e → “exception” function• p → “progress” function

• To store a Promise:• var storePromise = longTaskAsyncPromise();

Page 25: Html5

7 Advanced Topics

demo_workers.js: function sendMessage() { postMessage('MESSAGE'); } sendMessage();

• Web worker:• Is the only method to create threads. When executing scripts in an HTML page, the page becomes

unresponsive until the script is finished.• A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting

the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

function startWorker(){ if(typeof(Worker)!=="undefined") { if(typeof(w)=="undefined") { w=new Worker("demo_workers.js"); } w.onmessage = function (event) { // RESPONSE = event.data document.getElementById("result").innerHTML=event.data; }; } else { // THE BROWSER DOES NOT SUPPORT WEB WORKERS }}

function stopWorker(){ w.terminate();}

Page 26: Html5

7 Advanced Topics• Web sockets:

function WebSocketTest(){ if ("WebSocket" in window) { alert("WebSocket is supported by your Browser!"); // Let us open a web socket var ws = new WebSocket("ws://localhost:9998/echo"); ws.onopen = function() { // Web Socket is connected, send data using send() ws.send("Message to send"); alert("Message is sent..."); }; ws.onmessage = function (evt) { var received_msg = evt.data; alert("Message is received..."); }; ws.onclose = function() { // websocket is closed. alert("Connection is closed..."); }; } else { // The browser doesn't support WebSocket alert("WebSocket NOT supported by your Browser!"); }}

Page 27: Html5

8 Other topics• Regular expressions:

Valid a URL:^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \?=.-]*)*\/?$

Valid an E-Mail:^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$

Valid a phone number:^\+?\d{1,3}?[- .]?\(?(?:\d{2,3})\)?[- .]?\d\d\d[- .]?\d\d\d\d$

Valid a postal code: ^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$

Valid a username:^[a-z\d_]{4,15}$

Page 28: Html5

8 Other topics

• XMLHttpRequest with AJAX:

1.- Create the object XMLHttpRequest xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); xmlHttp = new XMLHttpRequest(); xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

2.- Send the information //Define the call var ajaxRequest = 'receptor.aspx?Info=' + MESSAGE; //Function for managing response xmlHttp.onreadystatechange = RecceiveInfo; //Send xmlHttp.open("GET", ajaxRequest, true); xmlHttp.send(""); //Send (other option) xmlHttp.open("POST", ajaxRequest, true); xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=ISO- 8859-1'); xmlHttp.send(XML);

3.- Get the information in the server private void GetInfoServer() { string info = Request.QueryString["info"]; // Tratar INFO HttpResponse response = HttpContext.Current.Response; response.Clear(); response.ContentType = "text/plain"; response.Write(s); response.Flush(); response.End(); } 4.- Receive the info from the server function RecceiveInfo() { if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { alert(xmlHttp.responseText); } }

Page 29: Html5

8 Other topics

• AJAX Call:

$.ajax({ url: "http://fiddle.jshell.net/favicon.png", beforeSend: function ( xhr ) { xhr.overrideMimeType("text/plain; charset=x-user-defined"); }} ) .done(function ( data ) { if( console && console.log ) { console.log("Sample of data:", data.slice(0, 100)); }});

if(typeof(Storage)!=="undefined") { localStorage.myvariable="Smith";} else { //NOT SUPPORTED}

if(typeof(Storage)!=="undefined") { sessionStorage.myvariable="Smith";} else { //NOT SUPPORTED}

• Local storage and Session storage:

Page 30: Html5

8 Other topics

• Geolocation:

var x=document.getElementById("demo");

function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML="Geolocation is not supported by this browser."; }}

function showPosition(position) { x.innerHTML="Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;}

• Serialization with JSon:

var object = {"name" : "mario", "surname" : "delgado picazo"};var serialized = JSON.stringify(object);var objectCopy = JSON.parse(serialized);

Page 31: Html5

9 JQueryjQuery Selectors

$("p").hide() -> Demonstrates the jQuery hide() method, hiding all <p> elements.

jQuery Events$("p").click(function(){ $(this).hide(); });

jQuery HTML Get Content and Attributestext() and html() -> Get content with the jQuery text() and html() methods.val() -> Get the value of a form field with the jQuery val() method.attr() -> Get the value of an attribute with the jQuery attr() method.

jQuery HTML Add Elements/Contentappend() -> Insert content at the end of the selected HTML elements.prepend() -> Insert content at the beginning of the selected HTML elements.append() -> Create new elements with text/HTML, jQuery, and JavaScript/DOM. Then append the new elements to the text.after() and before() -> Insert content after and before the selected HTML elements.after() -> Create new elements with text/HTML, jQuery, and JavaScript/DOM. Then insert the new elements after the selected

element.

jQuery HTML Remove Elements/Contentremove() -> Remove the selected element(s).empty() -> Remove all child elements of the selected element(s).remove() -> Filter the elements to be removed

jQuery Get and Set CSS ClassesaddClass() -> Add class attributes to different elements.addClass() -> Specify multiple classes within the addClass() method.removeClass() -> Remove a specific class attribute from different elements.toggleClass() -> Toggle between adding/removing classes from the selected elements.

Page 32: Html5

The End…?