Book: Head First HTML5 Programming

December 9th, 2014

Table of Contents

01. Getting to Know HTML5

02. Introducing JavaScript and the DOM

03. Events, Handlers and All that Jazz

04. JavaScript functions and Objects

(05. Geolocation)

06. Talking to the web

07. Canvas

08. Video

09. Web Storage

10. Web Workers

 


 

01. Getting to Know HTML5

minimal html5 document:

<!doctype html>

 

<html>

 

<head>

 

<meta charset="utf-8">

 

<linkrel="stylesheet"href="name.css">

 

<script src="src.js"></script>

 

</head>

 

<body></body>

 

</html>

<script> javascript code </script>

var name = "tekst";

var othername = 100;

while(condition){...}

if(condition){}

else{}

name = name + "<br>"; // string concatination

document.write(name); // write string at position of <script> tag

 


 

02. Introducing JavaScript and the DOM

var element = document.getElementById("idName");

element.innerHTML = "nieuwe tekst";

function initBlaBla() {...}

window.onload=initBlaBla;

var arr = new Array();

arr[1]="tests";

var arr = [4,8,6];

var length = arr.length;

Math.floor(x);

Math.random() * arr.length;

Book: David Flanagan - Javascript: The Definitive Guide

undefined != null

 


 

03. Events, Handlers and All that Jazz

H3: Events, Handlers, ... - Interaction

 

 

DOM: Document Object Model

 

 

adding a click listener to a button

button.onclick = handleButtonClick; // self defined function

function handleButtonClick(){

 

alert("Button was clicked");

 

}

access or edit value of input text field

txt.value = "new text"; // for input text fields

creating a DOM element and add it to the page

var li = document.createElement("li");

 

ul.appendChild(li);

 


 

04. JavaScript functions and Objects

 

 

 

Arguments VS Parameters:

fName(arg);

 

function fName(param){

return param;

}

parameters: pass-by-value

objects: pass-by-reference

function without return, returns 'undefined'

functions are values

 

 

Object Literals:

var obj = {

 

name : "name",

 

rank : 3,

 

arrName : ["elt0","elt1"],

 

methodName : function(){...}

}

 

obj.name;

 

obj["name"];

 

for(prop in obj){...}

 

 

Add/remove property to object

obj.newFieldName = "test";

 

delete obj.newFieldName; // undefined

 

 

current time:

new Date().getTime();

 

 

Function vs Method

  • function: global

  • method: object-bound

Constructor(function with statements using 'this')

function Dog(name, weight){

 

this.name= name;

 

this.weight = weight;

 

this.bark = function(){...};

 

}

var instance = new Dog("fido", 46);

Assigning a variable without 'var' makes it global, even when done in a function

 


 

06. Talking to the web

 

A) XHRorAJAX: XML Http Request

  • secure

  • only from same server as webpage

  • not only JSON

var request = new XMLHttpRequest();

 

request.open("GET", url);

 

request.onload = function() {

 

if (request.status == 200) {

 

alert("Data received!");

 

}

 

};

 

request.send(null); // or data you want to send

JSON: JavaScript Object Notation

JSON.stringify(movie);

 

JSON.parse(jsonString);

? WHY does 'for..in' not work but 'for i-n++' does work?

> because 'for..in' is more complicated than 'for..i-n++'

-----------------------------------------------------------------------------

B) JSONP: json with Padding

  • less secure

  • from ANY server

  • automatically parsed as JavaScript

  • usually callback function

var newScriptElement = document.createElement("script");

 

newScriptElement.setAttribute("src", url);

 

newScriptElement.setAttribute("id", "jsonp");

insert a script tag

<script src="http://externalsite.be/dog.json?q=hfhtml5&callback=myCallback"></script>

linking a file usually containing

var data = [{"name":"tw"},{"name":"other}]

 

myCallback(data);

 

 

Script injection: insert script tag with JavaScript

var head = document.getElementsByTagName("head")[0];

 

if(oldScriptElement == null){

 

head.appendChild(newScriptElement):

 

}else{

head.replaceChild(newScriptElement, oldScriptElement);

}

-----------------------------------------------------------------------------

Timer

setInterval(handleRefresh, 3000);

 

 

Anti-browser-cache

var url = "http://gumball.wickedlysmart.com/?callback=updateSales" +

"&random=" + (new Date()).getTime();

 

 


 

07. Canvas

 

canvas html tag

<canvas id="..." width="300" height="150">Msg when canvas not supported</canvas>

css width and height SCALE the canvas

var cancas = document.getElementById("...");

 

var context = canvas.getContext("2d");

stroke/fill

context.fillRect(x,y,width,height);

checksupport:

if(canvas.getContext){}

check support without canvas in html:

var cavas = document.createElement("canvas");

color(like CSS)

context.fillStyle = "lightblue";

 

 

// c --> context

Create paths:

c.beginPath();

 

c.moveTo(x,y);

 

c.lineTo(x,y);

 

...

 

c.closePath();

 

 

Draw paths:

c.lineWidth = 5

 

c.stroke();

 

c.fillStyle = "red";

 

c.fill();

 

 

Arcs:

angles in radial

direction true is counterClockwise

c.beginPath();

 

c.arc(x,y,radius, startAngle, endAngle, direction);

 

 

Text:

c.font = "italic 1.2em serif"; // cfcss

c.textAlign = "left";

c.fillText("text", x,y);

 

 

Image:

var img = new Image();

img.src = "url.png";

img.onload = function(){c.drawImage(img, x, y, width, hieght);}

 


 

08 Video

<video controls autoplay src="video/preroll.mp4" width="480" height="360" poster="images/prerollposter.jpg" id="video"></video>

attributes:

  • src="url": video file

  • width=""

  • height=""

  • controls: show controls

  • preload: load before play is clicked

  • autoplay: start playing when loaded

  • poster="imgSrc": show this image before playing

  • loop: auto replay

 

Video formats:

 

MP4: H264 video + AAC audio

  • safari

  • IE9

  • chrome?

Ogg: Theora video + Vorbis audio

  • firefox

  • chrome

  • opera

WebM: Vp8 video + Vorbis audio

  • firefox

  • chrome

  • opera

 

Fallback flash:

<object> tag in <video>

 

 

Extra's:

scratch buffer to process video before copying it to the display.

no HTML5 standard for streaming

no standard way of protecting video delivered through the video element

 


 

H9: Web Storage - storing things locally

localStorage/sessionStorage

 

---------------------------

 

length

 

---------------------------

 

setItem("key", "value")

 

getItem("key") : "value"

 

key(i) : "key"

 

removeItem("key")

 

clear()

 

 

Cookies:

  • size=4KB

  • key-value pairs

  • sent with every HTTP request

 

 

Web Storage:

  • size=5-10MB per domain

  • key-value pairs

  • private per browser, per domain

 

 

save/load:

localStorage.setItem("key", "value"); // overrides if key already exists

 

var valueString = localStorage.getItem("key");

or

localStorage["key"] = "value";

 

var value = localStorage["key"];

 

 

check if supported

if (window["localStorage"]) {...}

 

 

loopthrough whole storage: (undefined order)

for (var i = 0; i < localStorage.length; i++) {

 

var key = localStorage.key(i);

 

var value = localStorage[key];

 

}

 

 

FOR IN

for (var key in localStorage) {

 

var value = localStorage[key];

 

}

 

 

remove:

localStorage.removeItem("key");

 

 

Developer tools of a browser can show all local storage

 

 

use JSON to store arrays,objects,... in localstorage

 

 

Going over thequota:

try {

 

localStorage.setItem(myKey, myValue);

 

} catch(e) {

 

if (e == QUOTA_EXCEEDED_ERR) {}

 

}

 

 

Session Storage:

  • remove data on exit

  • "sessionStorage" instead of "localStorage"

 

 

? Does editing page source allow localStorage.clear() for that domain?

 


 

10 Web Workers

 

 

MAIN

 

 

check if workers areavailable:

if (window["Worker"]) {

 

var status = document.getElementById("status");

 

status.innerHTML = "Bummer, no Web Workers";

 

}

 

 

createworkers:

var worker = new Worker("worker.js");

 

var worker2 = new Worker("worker.js");

 

 

communicate(string, array, JSON, not functions):

worker.postMessage("ping");

 

 

worker.onmessage = function (event) {

 

var message = "Worker says " + event.data;

 

var worker = event.target;

 

};

 

 

WORKER

onmessage = pingPong;

 

function pingPong(event) {

 

if (event.data == "ping") {

 

postMessage("pong");

 

}

 

}

 

 

VARIA

 

 

scripts:

importScripts("http://bigscience.org/nuclear.js","mylibs/atomsmasher.js");

 

 

main:

worker.terminate();

worker:

close();

 

 

handle errors (main):

worker.onerror = function(error) {

 

document.getElementById("output").innerHTML ="There was an error in " + error.filename +" at line number " + error.lineno +": " + error.message;

 

}

 

 

workers can use

  • XMLHttpRequest

  • Local Storage