1. H 360 – H L5
R TM
Pr epar at i on (M ni ) G de
i ui
25.02.2013
Mario Delgado Picazo
2. AGENDA
1. Syllabus
2. Semantic Structure
3. CSS3 Selectors and Style Properties
4. Advanced layout and animation
5. Javascript Core Capabilities
6. DOM Interactions
7. Advanced Topics
8. Other topics
9. JQuery
3. 1 Syllabus
Implement and Manipulate Document Structures
and Objects (24%) Implement Program Flow (25%)
• Create the document structure. • Implement program flow.
• Write code that interacts with UI controls. • Raise and handle an event.
• Apply styling to HTML elements programmatically. • Implement exception handling.
• Implement HTML5 APIs. • Implement a callback.
• Establish the scope of objects and variables. • Create a web worker process.
• Create and implement objects and methods.
Use CSS3 in Applications (25%)
Access and Secure Data (26%) • Style HTML text properties.
• Validate user input by using HTML5 elements. • Style HTML box properties.
• Validate user input by using JavaScript. • Create a flexible content layout.
• Consume data. • Create an animated and adaptive UI.
• Serialize, deserialize, and transmit data. • Find elements by using CSS selectors and jQuery.
• Structure a CSS file by using CSS selectors.
Test information: http://www.microsoft.com/learning/en/us/exam.aspx?id=70-480
4. Tag Description
<article> Defines an article
2 Semantic Structure
<aside> Defines content aside from the page content
Isolates a part of text that might be formatted in a
<bdi>
different direction from other text outside it
<command> Defines a command button that a user can invoke
• Structure <details>
Defines additional details that the user can view or
hide
<summary> Defines a visible heading for a <details> element
Specifies self-contained content, like illustrations,
<figure>
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
Groups a set of <h1> to <h6> elements when a
<hgroup>
heading has multiple levels
<mark> Defines marked/highlighted text
Defines a scalar measurement within a known
<meter>
range (a gauge)
<nav> Defines navigation links
<progress> Represents the progress of a task
Defines what to show in browsers that do not
<rp>
support ruby annotations
<section> Defines a section in a document
<time> Defines a date/time
6. 3 CSS3 Selectors and Style Properties
<audio controls autoplay loop preload="auto">
• Media tags <source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Tag Description Your browser does not support the audio element.
<audio> Defines sound content </audio>
<video> Defines a video or movie or
Defines multiple media <audio src="horse.ogg" controls autoplay loop
<source> resources for <video> and preload="auto"></audio>
<audio>
Defines a container for an <video autoplay loop muted width="320" height="240" controls
<embed> external application or preload=”node”>
interactive content (a plug-in) <source src="movie.mp4" type="video/mp4">
Defines text tracks for <video> <source src="movie.ogg" type="video/ogg">
<track> Your browser does not support the video tag.
and <audio>
</video>
or
<video src="movie.ogg" controls>Your browser does not support
the video tag.</video>
7. 3 CSS3 Selectors and Style Properties
• Canvas vs. SVG
Canvas SVG
• Resolution dependent • Resolution independent
• No support for event handlers • Support for event handlers
• Poor text rendering capabilities • Best suited for applications with large rendering areas
• You can save the resulting image as .png or .jpg (Google Maps)
• Well suited for graphic-intensive games • Slow rendering if complex
• Not suited for game applications
<canvas id="myCanvas" width="200" height="100" <svg width="200" height="200">
style="border:1px solid #000000;"> <rect fill=rgb(0,0,255) x="10" y="10" width="180"
Your browser does not support this Canvas! height="180">
</canvas> </svg>
<script> <svg height="200">
var c=document.getElementById("myCanvas"); <polygon points="100,10 40,180 190,60 10,60 160,180"
var ctx=c.getContext("2d"); style="fill:lime;stroke:purple;stroke-width:5;fill-
rule:evenodd;">
ctx.fillStyle="#FF0000";
</svg>
ctx.fillRect(0,0,150,75);</script>
8. 3 CSS3 Selectors and Style Properties
Selector Example Example description
.class .intro Selects all elements with class="intro"
• Selectors #id
*
#firstname
*
Selects the element with id="firstname"
Selects all elements
element p Selects all <p> elements
element,element div,p Selects all <div> elements and all <p> elements
element element div p Selects all <p> elements inside <div> elements
element>element div>p Selects all <p> elements where the parent is a <div> element
element+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"
9. 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
10. 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)
11. 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)
}
12. 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%))
13. 4 Advanced layout and animation
Tag Description
static Default. Elements render in order, as they appear in the document flow
• Positioning absolute The element is positioned relative to its first positioned (not static) ancestor element
fixed The element is positioned relative to the browser window
The element is positioned relative to its normal position, so "left:20" adds 20 pixels to the element's LEFT
relative
position
inherit The value of the position property is inherited from the parent element
14. 4 Advanced layout and animation
Tag Description
• Display none
box (or flex-box)
The element will not be displayed at all
The element is displayed as a block-level flex container box
block The element is displayed as a block-level element (like paragraphs and headers)
flex The element is displayed as a block-level flex container box
inline This is default. The element is displayed as an inline-level element (like span)
The element is placed as an inline element (on the same line as adjacent content), but it
inline-block
behaves as a block element
inline-flex The element is displayed as an inline-level flex container box
inline-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 table
table-caption The element is displayed as a table caption
table-cell The element is displayed as a table cell
table-column The element is displayed as a table column
table-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 group
table-header-group The element is displayed as a table header row group
table-row The element is displayed as a table row
table-row-group The element is displayed as a table row group
inherit The value of the display property will be inherited from the parent element
15. 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
16. 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.
17. 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 %.
18. 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
19. 5 Javascript Core Capabilities
• Arrays
Var 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 others
elements, 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 has
length > 5.
• Fruit.some(function(i) { return (i.length>5); }); -> like every, but some.
20. 5 Javascript Core Capabilities
function auto(aBrand, aModel, aColor) {
this.brand = aBrand;
• Objects this.model = aModel;
var dog = {}; this.color = aColor;
this.selectBrand = function selectBrand(otherBrand){
dog.breed = “German Shepherd”; this.brand = otherBrand
dog.bark = function() { alert('Guau!'); } };
this.selectModel = function selectModel(otherModel){
var dog = { this.model = otherModel
breed : “German Shepherd”, };
bark : function() { alert('Guau!') this.howItIs = function howItIs(){
return "Brand: " + this.brand + "<br />" +
} "Model: " + this.model + "<br />" +
var dog = { "Color: " + this.color;
};
“breed” : “German Shepherd”,
}
“bark” : function() { alert('Guau!')
} <script>
var firstCar = new auto("Volkswagen", "Golf", "Rojo");
document.getElementById("div1").innerHTML = firstCar.howItIs();
</script>
JSON syntax: the double commas are mandatory and cannot add functions:
{“breed” : “German Shepherd”}
21. 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>>).
22. 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>
23. 7 Advanced Topics
• Handling exceptions
• Minimizing failures in code
• Managing failures in code
try {
//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;
//or
throw 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.
24. 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();
25. 7 Advanced Topics
• 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")
{ demo_workers.js:
w=new Worker("demo_workers.js");
}
function sendMessage()
w.onmessage = function (event) { {
// RESPONSE = event.data
document.getElementById("result").innerHTML=event.data; postMessage('MESSAGE');
};
} else {
}
// THE BROWSER DOES NOT SUPPORT WEB WORKERS sendMessage();
}
}
function stopWorker()
{
w.terminate();
}
26. 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!");
}
}
27. 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}))?[- .]?ddd[- .]?dddd$
Valid a postal code:
^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$
Valid a username:
^[a-zd_]{4,15}$
28. 8 Other topics
• XMLHttpRequest with AJAX:
1.- Create the object XMLHttpRequest 3.- Get the information in the server
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); private void GetInfoServer()
xmlHttp = new XMLHttpRequest(); {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); string info = Request.QueryString["info"];
// Tratar INFO
HttpResponse response = HttpContext.Current.Response;
2.- Send the information
response.Clear();
//Define the call
response.ContentType = "text/plain";
var ajaxRequest = 'receptor.aspx?Info=' + MESSAGE; response.Write(s);
//Function for managing response response.Flush();
xmlHttp.onreadystatechange = RecceiveInfo; response.End();
//Send }
xmlHttp.open("GET", ajaxRequest, true);
xmlHttp.send(""); 4.- Receive the info from the server
//Send (other option) function RecceiveInfo()
xmlHttp.open("POST", ajaxRequest, true); {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-
form-urlencoded; charset=ISO- {
8859-1'); alert(xmlHttp.responseText);
}
xmlHttp.send(XML);
}
30. 8 Other topics
• Geolocation: • Serialization with JSon:
var x=document.getElementById("demo"); var object = {"name" : "mario", "surname" : "delgado picazo"};
var serialized = JSON.stringify(object);
function getLocation() { var objectCopy = JSON.parse(serialized);
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;
}
31. 9 JQuery
jQuery Selectors
$("p").hide() -> Demonstrates the jQuery hide() method, hiding all <p> elements.
jQuery Events
$("p").click(function(){ $(this).hide(); });
jQuery HTML Get Content and Attributes
text() 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/Content
append() -> 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/Content
remove() -> 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 Classes
addClass() -> 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.