Modern JavaScript, HTML5 and CSS3 techniques and examples. There’s an endless amount of materials available around these topics so naturally this set doesn’t cover everything there is to know. Instead this is more like a summary of good techniques and practices I’ve encountered while doing web software development.
4. Perttu Myry 6.11.2012
JavaScript
Introduction
Is no a subset of Java and actually has very
little similarities with Java
Formalized as ECMAScript language
“JavaScript is a prototype-based scripting
language that is dynamic, weakly typed and
has first-class functions. It is a multi-paradigm
language, supporting object-oriented,
imperative, and functional programming
styles.”
WikiPedia
5. Perttu Myry 6.11.2012
JavaScript
Introduction
Has been available for long time (for example
from Netscape 2 which was introduced in
1996)
Both language and engines have been
evolving ever since
Primarily used in browsers
Can be executed outside browser using, for
example, Rhino or Google’s V8 JavaScript
engine
For example, increasingly popular Node.js
platform is based on V8
6. Perttu Myry 6.11.2012
JavaScript
Introduction
<!-- JavaScript can be written in many ways -->
<!-- external script -->
<script type="text/javascript" src="js/someFile.js"></script>
<!-- script block -->
<script type="text/javascript">
alert('Hello world');
</script>
<!-- inline (bad practise, avoid!) -->
<div style="background: blue;"
onmouseover="this.style.background = 'red';"
onmouseout="this.style.background = 'blue';">
This div has blue background that changes to red on mouse over
</div>
7. Perttu Myry 6.11.2012
JavaScript
Introduction
// Here we create same global variable in four different ways
// Using var statement in global scope
// (scope means the context (function) in which the code is executed)
var title = 'some string';
// All global variables become part of native window object
// Setting object property via dot notation
window.title = 'some string';
// Setting object property via square bracket notation
window['title'] = 'some string';
function doSomething() {
// Variable without var statement makes it
// always global regardless of scope
title = 'some string';
}
doSomething();
8. Perttu Myry 6.11.2012
JavaScript
Introduction
// Two popular ways of writing functions in JavaScript
// Traditional way to write a function
function doSomething(someAttribute) {
// Do something here...
}
// In JavaScript function is standard datatype (an object),
// they can be passed around and copied freely,
// here we copy anonymous function into doSomething variable
var doSomething = function(someAttribute) {
// Do something here...
}
// Executing function...
doSomething('some value');
9. Perttu Myry 6.11.2012
JavaScript
DOM
Introduction
DOM
Events and Feature Detection
AJAX and JSON
Animations
Object-Oriented JavaScript
Unobtrusive JavaScript
Debugging
jQuery
10. Perttu Myry 6.11.2012
JavaScript
DOM
“Interaction with the DOM is usually slower than normal JavaScript code”
JavaScript Performance Best Practices, Nokia Developer Wiki
11. Perttu Myry 6.11.2012
JavaScript
DOM
“The Document Object Model (DOM) is the model
that describes how all elements in an HTML page,
like input fields, images, paragraphs etc., are
related to the topmost structure: the document
itself. By calling the element by its proper DOM
name, we can influence it.”
QuirksMode
DOOM = Especially in old browsers poorly written
DOM code can lead to horrible performance
JavaScript engines’ DOM performance has been
dramatically increased in modern browsers
12. Perttu Myry 6.11.2012
JavaScript
DOM
Each item in DOM is a Node
DOM can be walked through using
various methods, such as firstChild,
lastChild, childNodes and parentNode
Elements can be fetched using methods
such as document.getElementById() or
document.getElementsByTagName()
13. Perttu Myry 6.11.2012
JavaScript
DOM
<!-- Some HTML code -->
<div id="contentWrapper">
<p>First paragraph, here is a link to
<a class="external" href="http://www.google.fi/">Google</a>
</p>
<p>This is second paragraph.</p>
</div>
<script type="text/javascript">
var wrapper = document.getElementById('contentWrapper');
// wrapper's first child is text (line break), its next sibling is the
// first paragraph which first child (array index 0) is text and
// second child (array index 1) is the link
// alerts http://www.google.fi/
alert(wrapper.firstChild.nextSibling.childNodes[1].href);
// same end result but easier, alerts http://www.google.fi/
alert(document.getElementsByTagName('a')[0].href);
</script>
http://jsfiddle.net/U3ckA/
14. Perttu Myry 6.11.2012
JavaScript
DOM
Travelling DOM like this is both worksome
and code breaks rather easily if HTML
structure changes
Attaching unique id attribute to each
element that you want to access via
JavaScript could solve problems with
HTML structure changing, but it isn't very
flexible option either
Let's take a look at CSS selectors
15. Perttu Myry 6.11.2012
JavaScript
DOM
<!-- Some HTML code -->
<a href="go/back/to/previous/page.html">Back</a>
<div id="contentWrapper">
<p>First paragraph, here is a link to
<a class="external" href="http://www.google.fi/">Google</a>
</p>
<p>This is second paragraph.</p>
</div>
<script type="text/javascript">
// now first anchor element is back link, alerts page.html
alert(document.getElementsByTagName('a')[0].href);
// modern browser support native CSS selectors
if(document.querySelectorAll) {
// find all anchors which have class name external
// alerts http://www.google.fi/
alert(document.querySelectorAll('a.external')[0].href);
}
</script>
16. Perttu Myry 6.11.2012
JavaScript
DOM
<!-- Okay and then something potentially useful, not just alerting stuff -->
<a class="external" href="http://www.google.fi/">Google</a><br />
<a class="external nounderline" href="http://www.w3.org/">W3C</a><br />
<a href="link/to/some/internal/page.html">page.html</a>
<script type="text/javascript">
// For example, in strict XHTML document type, anchor target attribute is not
// allowed though it works in every modern browser, let's use JavaScript to make
// HTML code valid and yet class="external" links open in new browser window/tab
if(document.querySelectorAll) {
var anchors = document.querySelectorAll('a.external');
var count = anchors.length; // NB. not checking length again in each loop
/*for(var i=0; i<count; i++) {
anchors[i].target = '_blank';
}*/
while(count--) {
anchors[count].target = '_blank';
}
}
</script>
http://jsfiddle.net/ZAGsB/
17. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
Introduction
DOM
Events and Feature Detection
AJAX and JSON
Animations
Object-Oriented JavaScript
Unobtrusive JavaScript
Debugging
jQuery
18. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
Event model provides efficient way to
decouple (avoid unnecessary dependencies)
Information is delivered as events and
handled via event handler functions
JavaScript has lots of native events, such as
mouseover, mouseout, click etc.
External libraries, such as jQuery, can provide
option to trigger and handle also custom
events
Let’s take a look at DOM event flow
19. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
20. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
<!-- Event handler can be registered in four different ways:
inline, traditional, W3C and Microsoft -->
<!– inline (again, bad practice, avoid!) -->
<td onclick="alert('click over table cell');">Over the River, Charlie</td>
<script type="text/javascript">
// declare variable td and function fn
var td = document.getElementsByTagName('td')[1];
function fn(e) {
alert('click over table cell');
};
// traditional (okay, but setting new handler overrides previous one)
td.onclick = fn;
// W3C (supported by all modern browsers [event type, handler, use capturing])
td.addEventListener('click', fn, false);
// MS (before IE 9, notice "on" before event type and does not support capturing)
td.attachEvent('onclick', fn);
</script>
21. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
Feature detection is needed because different
browsers support different JavaScript versions and
functionality
Possibility to provide better user experience for
modern browsers and yet graceful fallback for old
browsers
Why not just do browser detection?
Because user agent information is not reliable and
new versions of browsers can fix an error that exists
in current version of the browser causing you
additional overhead and maintenance
22. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
// Example why you should avoid browser detection, assuming
// this code was written before Internet Explorer 9 was released.
function bind(element, eventType, fn) {
if(navigator.userAgent.match(/msie/i)) {
// IE specific way of adding event listener
element.attachEvent('on' + eventType, fn);
} else {
// W3C compatible browsers
element.addEventListener(eventType, fn, false);
}
}
bind(document.getElementById('someButton', 'click', function(e) {
alert('element with id="someButton" was clicked');
}));
23. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
So what went wrong with browser detection?
IE 9 introduced W3C compatible
addEventListener which all other major
browser had been using
Actually in this case IE 9 still supports
attachEvent, but we cannot know whether
attachEvent will be removed in some future IE
version
When we write code we cannot foresee all
these kind of changes, what can we do?
24. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
// Fixed example using feature detection that works in "all" browsers
function bind(element, eventType, fn) {
if(element.addEventListener) {
// W3C compatible browsers
element.addEventListener(eventType, fn, false);
} else if(element.attachEvent) {
// Old IE specific way of adding event listener
element.attachEvent('on' + eventType, fn);
} else {
// Oldest browsers support neither, could write lengthy
// fallback which could mimic W3C/MS models, but in this
// case we simply don't support old browsers
alert('Sorry, this application does not support old browsers');
}
}
25. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
// Usage examples
bind(document.getElementById('someButton'), 'click', function(e) {
alert('element with id="someButton" was clicked');
});
bind(document.getElementById('someInput'), 'keyup', function(e) {
var event = e || window.event;
// Force input value to lower case
this.value = this.value.toLowerCase();
// If user hits "enter" we call doSearch() method
if(event.keyCode === 13) {
doSearch();
}
});
26. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
// Event triggering
function trigger(element, eventType) {
var event;
if(document.createEvent) {
// W3C compatible browsers
event = document.createEvent('HTMLEvents');
event.initEvent(eventType, true, true);
} else if(document.createEventObject) {
// Old IE specific syntax
event = document.createEventObject();
event.eventType = 'on' + eventType;
} else {
// Not supporting oldest browsers
alert('Sorry, this application does not support old browsers');
return;
}
event.eventName = eventType;
if(document.createEvent) {
element.dispatchEvent(event);
} else {
element.fireEvent(event.eventType, event);
}
}
27. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
<!-- Usage examples -->
<div class="inputRow">Row #1: <input type="text" /> <span class="button">Save</span></div>
<div class="inputRow">Row #2: <input type="text" /> <span class="button">Save</span></div>
<div class="inputRow">Row #3: <input type="text" /> <span class="button">Save</span></div>
<!-- and so on... -->
<script type="text/javascript">
function doSave(value) {
alert('value saved: ' + value);
}
function getEvent(e) {
return e || window.event; // old IE browsers store event in window object
}
function getTarget(event) {
return event.target || event.srcElement; // and there are differences in event attributes
}
// continue on next slide...
28. Perttu Myry 6.11.2012
JavaScript
Events and Feature Detection
var inputRows = document.querySelectorAll('div.inputRow'), i = inputRows.length;
while(i--) {
// bind click event handler to all span elements in input row
bind(inputRows[i].getElementsByTagName('span')[0], 'click', function(e) {
var target = getTarget(getEvent(e));
if(this.className.match(/disabled/)) {
return;
}
this.className += ' disabled'; // disable save button once it has been clicked once
// do something with the data in this row...
doSave(target.parentNode.getElementsByTagName('input')[0].value);
});
// bind keyup event handler to all input elements in input row
bind(inputRows[i].getElementsByTagName('input')[0], 'keyup', function(e) {
var event = getEvent(e);
var target = getTarget(event);
if(event.keyCode === 13) {
trigger(target.parentNode.getElementsByTagName('span')[0], 'click');
}
});
}
</script>
http://jsfiddle.net/PhVpk/
29. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
Introduction
DOM
Events and Feature Detection
AJAX and JSON
Animations
Object-Oriented JavaScript
Unobtrusive JavaScript
Debugging
jQuery
30. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
AJAX = Asynchronous JavaScript and XML
”AJAX allows web pages to be updated
asynchronously by exchanging small amounts
of data with the server behind the scenes. This
means that it is possible to update parts of a
web page, without reloading the whole
page.”
W3Schools AJAX Tutorial
You might also encounter term AJAJ which
stands for Asynchronous JavaScript and JSON
31. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
Based on XMLHttpRequest object that can be
used to make HTTP request as a background
operation
Why AJAX?
Enhanced user experience
Better performing web sites and applications (it is
much faster to fetch and update only small part of
the page versus reloading the whole page)
Can be used to assemble data from various
sources to a single page
Check out iGoogle
32. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
function ajax(url, fn) {
var req;
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
// once again, old IE implementation differs from W3C
req = new ActiveXObject('Microsoft.XMLHTTP');
}
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
fn(req.responseText);
}
}
req.open('GET', url, true);
req.send();
}
33. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
// Notice that these requests are asynchronous. This means that
// calling ajax(someUrl) does not stop JavaScript execution until
// response is received. This also means we have no way of knowing
// which one of these requests will receive response first.
ajax('some/test/file.txt', function(response) {
alert('Fetched file.txt content using AJAX: ' + response);
});
ajax('another/site/page.html', function(response) {
alert('Fetched page.html content using AJAX: ' + response);
});
34. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
JSON = JavaScript Object Notation
XML is one of the most used data exhance
formats, but in JavaScript JSON format is more
straightforward
Backends support JSON very well
For example, in PHP 5.2 JSON is enabled by
default and Zend_Json can be used to make
XML-to-JSON conversion (useful in case your
application is currently using XML and you
want to switch to use JSON in certain cases)
JSON example messages
35. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
<!-- Modern browsers have built-in support for JSON via global JSON
object, JSON2 library can be used to support older browsers
(JSON2 is light and uses native JSON object if one is available) -->
<script type="text/javascript" src="json2.js"></script>
<script type="text/javascript">
var myObject = {
'name' : 'John',
'age' : 43
};
// Convert object into JSON string
var jsonString = JSON.stringify(myObject);
// Convert JSON string back to JavaScript object
var myObject = JSON.parse(jsonString);
</script>
36. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
Doing cross domain AJAX requests doesn’t work
because of same origin policy
Best solution is to create a resource on your own
server which then makes the cross domain request
(no policy issues and you can cache results)
In case you have control over your server
environment, you can also use Cross-origin
resource sharing (CORS) to allow AJAX requests
from certain domains
If you are not in control of the server, you might still
be able to use JSONP (if server supports this
technique)
http://jsfiddle.net/q3sEC/4/
37. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
Be careful though when using JSONP
It adds new script tag to your page
Contents of the script are controlled by third party
Therefore load data only from sites which you trust
Malicious sites can exploit this and inject harmful
code into your site
Response could be something like /*harmful JS
code here*/ + yourCallbackFnName(/*json data
here*/)
This way it would look like request works correctly,
but also harmful JS code would be executed
38. Perttu Myry 6.11.2012
JavaScript
AJAX and JSON
<!-- JSONP technique exploits script tag which is not restricted to same
domain policy as XMLHttpRequest is -->
<script type="text/javascript">
// Define callback function
function myCallbackFunction(json) {
// do something with json data here...
};
// Create script element
var scriptTag = document.createElement('script');
// Set script src to a twitter feed, adding callback param wraps
// the response into myCallbackFunction(/*json data here*/);
scriptTag.src =
'https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&
include_rts=true&screen_name=twitterapi&count=2&callback=myCallbackFunction';
// Append the script to document head
document.getElementsByTagName('head')[0].appendChild(scriptTag);
</script>
40. Perttu Myry 6.11.2012
JavaScript
Animations
When transition between two different stages
is done in 2 or more steps which are not
executed at once, it can be considered as
an animation
In JavaScript this could be, for example,
change of position, size, color or opacity
Well designed animations look good and can
enhance user experience
Poorly designed and/or implemented
animations look bad, are annoying and will
make user experience worse
41. Perttu Myry 6.11.2012
JavaScript
Animations
So according to definition changing, for
example, element width from 100px to 200px
is not animated if it’s done
either in one step
or in n steps, but all steps are executed
immediately without any delay
In order not to execute all steps immediately,
we need to wait between steps
Traditionally this can be achieved either via
setTimeout or setInterval methods
42. Perttu Myry 6.11.2012
JavaScript
Animations
<div id="someBox" style="position: absolute; left: 0; top: 10px;">
I am a box
</div>
<script type="text/javascript">
var box = document.getElementById('someBox'), left = 0;
function moveBox() {
box.style.left = (left += 5) + 'px';
}
// setTimeout will call function once, box will move 5 pixels to
// right 100 milliseconds after this function call and stop
setTimeout(moveBox, 100);
// setInterval will call function again and again, box will move
// 5 pixels to every 20th millisecond
setInterval(moveBox, 20);
</script>
http://jsfiddle.net/rk4fH/1/
43. Perttu Myry 6.11.2012
JavaScript
Animations
My box just keeps on running and
eventually floats outside screen, how
about stopping the animation?
setTimeout and setInterval methods return
unique id which can be used to cancel
the timeout via clearTimeout(id) or
clearInterval(id) methods
44. Perttu Myry 6.11.2012
JavaScript
Animations
// Let's do bit different version of moveBox function
function moveBox(amount, max) {
// Left value is string like '15px', parseFloat converts that to number 15
var newLeft = parseFloat(box.style.left) + amount;
box.style.left = newLeft + 'px';
if(newLeft > max) {
return false;
}
return true;
}
var intervalId = setInterval(function() {
// Move box 5px more to right in each step every 10ms
// until it goes 500px from the left, this means that
// animation duration is 500 / 5 * 10ms = 1000ms = 1s
if(moveBox(5, 500) === false) {
clearInterval(intervalId);
}
}, 10);
http://jsfiddle.net/rk4fH/2/
45. Perttu Myry 6.11.2012
JavaScript
Animations
Animating like this is quite a bit of work and
doesn’t seem very flexible
In addition, setTimeout and setInterval are not
accurate (function might be executed some
milliseconds late because it’s placed on queue)
Modern browser support a method called
requestAnimationFrame which can be used to
create better performing, more accurately
executed and thus also smoother animations
In jQuery chapter we’ll take another look at
animations and how they can be done quite
much easier and more flexibly
47. Perttu Myry 6.11.2012
JavaScript
Object-Oriented JavaScript
OOP in JavaScript differs from traditional
languages
JavaScript doesn’t have traditional way
of creating classes, defining public,
protected or private variables and
methods inside class
Some things in JavaScript are not possible,
such as defining protected variables or
methods
48. Perttu Myry 6.11.2012
JavaScript
Object-Oriented JavaScript
// Define a new class Car
function Car(model) {
// Keyword this points to current object
// Public property model
this.model = model;
// Private variable carColor (only visible in this scope)
var carColor = 'Red';
// Public setter and getter for color (visible outside this scope)
this.getColor = function() {
return carColor;
};
this.setColor = function(color) {
carColor = color;
};
}
49. Perttu Myry 6.11.2012
JavaScript
Object-Oriented JavaScript
// Create new Car
var ford = new Car('Ford');
alert(ford.model); // Alerts "Ford"
alert(ford.getColor()); // Alerts "Red" (default)
ford.setColor('Blue'); // Change ford color
alert(ford.getColor()); // Alerts "Blue"
// Testing that variable carColor really is private
// Alerts undefined (carColor is not public property of Car)
alert(ford.carColor);
// Alerts undefined (variable carColor is not in global scope)
alert(carColor);
50. Perttu Myry 6.11.2012
JavaScript
Object-Oriented JavaScript
The dangerous keyword this
In JavaScript keyword this points to the
"owner" of the function
Powerful concept, but often causes problems
due misunderstanding or misusing
It's crucial to understand the difference of
copying a function compared to referring to
a function
Can be affected via call or apply functions
51. Perttu Myry 6.11.2012
JavaScript
Object-Oriented JavaScript
<!-- Few examples of common ways to misuse this -->
<div id="testElement"></div>
<script type="text/javascript">
function highlight() {
this.style.backgroundColor = '#d00';
};
this === window; // true
highlight(); // causes error, because window.style is undefined
// copy function to onmouseover
document.getElementById('testElement').onmouseover = highlight;
</script>
<!-- refer to function, this points to window and causes error -->
<div onmouseover="highlight();"></div>
<!-- force this point to div element using call function -->
<div onmouseover="highlight.call(this);"></div>
52. Perttu Myry 6.11.2012
JavaScript
Object-Oriented JavaScript
// OOP example of how keyword this can be misused
var Person = function(nickname) {
this.nickname = nickname;
};
// New methods to classes can be introduced via prototype
Person.prototype.sayName = function() {
alert(this.nickname);
};
var john = new Person('John');
var jane = new Person('Jane');
john.sayName(); // Alerts "John"
// Here we copy the function to global variable (owned by window object)
var sayJohnName = john.sayName;
// And now keyword "this" points to global window object
sayJohnName(); // Alerts undefined
// Function call or apply can be used to define where "this" points
sayJohnName.call(john); // Alerts "John"
sayJohnName.call(jane); // Alerts "Jane"
53. Perttu Myry 6.11.2012
JavaScript
Object-Oriented JavaScript
// Singleton pattern in JavaScript suggested by Douglas Crockford
var CarFactory = (function() {
// Variables created inside this scope are private
var createdModels = [];
// Return object which contains all public methods
return {
createCar : function(model) {
var car = {};
car.model = model;
createdModels.push(model);
return car;
},
countCreatedModels : function() {
alert(createdModels.length);
},
alertCreatedModels : function() {
alert(createdModels.join(', '));
}
};
})(); // executes function, CarFactory will now contain what the function returns
CarFactory.createCar('Ford');
CarFactory.createCar('Dodge');
CarFactory.createCar('Hyundai');
CarFactory.countCreatedModels(); // Alerts 3
CarFactory.alertCreatedModels(); // Alerts "Ford, Dodge, Hyundai"
55. Perttu Myry 6.11.2012
JavaScript
Unobtrusive JavaScript
Modern aproach to writing JavaScript
Separate functionality and content (do not
use inline JavaScript)
Follow JavaScript best practises (proper use of
design patterns, namespacing code, feature
detection, systematic testing...)
Progressive enhancements / gracefull
fallbacks to enhance user experience for
modern browsers and yet avoid fatal errors in
older browsers
56. Perttu Myry 6.11.2012
JavaScript
Unobtrusive JavaScript
<!-- Old school ugly way to write JavaScript -->
<a href="javascript:fetchNews();">Show 10 latest news</a>
<script type="text/javascript">
// introducing global function fetchNews
function fetchNews() {
// fetch 10 latest news here using AJAX...
};
</script>
57. Perttu Myry 6.11.2012
JavaScript
Unobtrusive JavaScript
<!-- Better in terms of decoupling plus does not introduce new
global function fetchNews, but this does nothing if JavaScript
support has been disabled in browser settings -->
<a href="#" id="fetchNews">Show 10 latest news</a>
<script type="text/javascript">
bind(document.getElementById('fetchNews'), 'click', function(e) {
// fetch 10 latest news here using AJAX...
});
</script>
58. Perttu Myry 6.11.2012
JavaScript
Unobtrusive JavaScript
<!-- Proper unobtrusive way is to provide fallback. Now if
JavaScript is enabled system will fetch news using AJAX,
but in JavaScript disabled environments browser will open
latestNews.php script and thus site will always work. -->
<a href="latestNews.php" id="fetchNews">Show 10 latest news</a>
<script type="text/javascript">
bind(document.getElementById('fetchNews'), 'click', function(e) {
var event = e || window.event;
// prevents browser to go to latestNews.php
event.preventDefault();
// fetch 10 latest news here using AJAX...
});
</script>
59. Perttu Myry 6.11.2012
JavaScript
Unobtrusive JavaScript
// Let’s imagine you are creating an application Custom Cars, this application will be big
// so you decide to create few different classes to handle different kind of functionality
function CustomCarsFactory() {/* factory code here*/};
function CustomCarsTires() {/* tires code here*/};
function CustomCarsBling() {
this.addSpinners = function(car) {/* add spinners to tire rims... */};
};
function CustomCarsShop = new function() {
// custom cars shop code here...
};
var factory = new CustomCarsFactory();
var tires = new CustomCarsTires();
var bling = new CustomCarsBling();
var myCar = factory.makeCar();
tires.makeTires(myCar);
bling.addSpinners(myCar);
shop.sellCar(myCar);
// Declared total of 8 global variables, could this be done any better?
60. Perttu Myry 6.11.2012
JavaScript
Unobtrusive JavaScript
// Use namespacing and singleton pattern
var CustomCars = (function() {
return {
Factory : function() {
return {
createCar : function() {
// here we create a new car...
},
Tires : function() {
return {
makeTires : function(car) {
// here we create tires to the car...
}
};
}(),
Bling : function() {
return {
addSpinners : function(car) {
// add spinners to tire rims...
}
};
}()
};
}()
};
})(); // executes function, CustomCars will now contain what the function returns
// Continue on next slide...
61. Perttu Myry 6.11.2012
JavaScript
Unobtrusive JavaScript
// On previous page we added indentation quite quickly, here is another
// way to add public methods to CustomCars singleton class without going
// wild with indentation
CustomCars.Shop = function() {
return {
sellCar : function(car) {
// here we sell cars...
alert('car sold :)');
}
};
}();
// Use Immediately-Invoked Function Expression (IIFE) to avoid polluting global scope
(function() {
// Here we are working in local scope,
// thus myCar will not become global variable
var myCar = CustomCars.Factory.createCar();
CustomCars.Factory.Tires.makeTires(myCar);
CustomCars.Factory.Bling.addSpinners(myCar);
CustomCars.Shop.sellCar(myCar);
})();
http://jsfiddle.net/xNX5q/2/
63. Perttu Myry 6.11.2012
JavaScript
Debugging
Modern browsers provide good
JavaScript debug tools
Firebug for Firefox
Chrome Developer Tools
IE Developer Tools (starting from IE 8)
Opera Dragonfly
Eachprovides a console into which
developers can log statements
64. Perttu Myry 6.11.2012
JavaScript
Debugging
Firebug and Chrome provide excellent tools
which can be used also for creating
breakpoints, checking network connections,
inspecting DOM tree, manipulating HTML and
CSS on the fly, collecting profiles and so on
Firebug Lite can be used, for example, for old
Internet Explorer browsers (IE 6+)
Not as complete as Firebug, but provides
many useful features, such on console
logging, HTML inspection and CSS
manipulation
65. Perttu Myry 6.11.2012
JavaScript
Debugging
// Console grouping and logging
console.group('fruits');
console.log('apple');
console.debug('orange');
console.info('banana');
console.warn('pineapple');
console.error('peach');
console.groupEnd();
// Tracing
(function() {
var test = function() {
console.trace();
};
test();
})();
// More complete example available at http://jsfiddle.net/XdRWt/
66. Perttu Myry 6.11.2012
JavaScript
Debugging
Word of warning: old browsers do not support
global console variable so leaving console.log()
statements in your code will cause errors in old
browsers
You can remove all your debug code before it
goes to production
Or you can write simple console support for old
browsers (http://jsfiddle.net/CWHj6/)
And there are also ready made solutions which
you can utilize
http://benalman.com/projects/javascript-debug-
console-log/
68. Perttu Myry 6.11.2012
JavaScript
jQuery
So far we have noticed that there are
quite a lot of browser inconsistencies and
we’ve just scratched the surface here
Writing cross-browser compatible
JavaScript isn’t easy
Though browsers in use are continuously
renewing, there are still lots of old browser
versions used worldwide
70. Perttu Myry 6.11.2012
JavaScript
jQuery
”jQuery is a fast and concise JavaScript
Library that simplifies HTML document
traversing, event handling, animating,
and Ajax interactions for rapid web
development. jQuery is designed to
change the way that you write
JavaScript.”
jquery.com
71. Perttu Myry 6.11.2012
JavaScript
jQuery
There are many JavaScript libraries out there, but
so far I have found jQuery to be the best, why so?
It’s lightweight (only one file, doesn’t cause
multiple HTTP requests such as, for example, Dojo
does in certain cases)
It’s well documented and easy to learn (check out
tutorials, use Google and check out
api.jquery.com)
It has a great way to utilize CSS selectors
It’s constantly evolving
It performs very well
It has a good plugin system
72. Perttu Myry 6.11.2012
JavaScript
jQuery
// jQuery and its CSS selectors can be used via global variable $
// (or jQuery), let's take a look at some new and previous
// examples how to use jQuery
// alerts how many external anchors there are on the page
alert(jQuery('a.external').length);
// Setting external anchors' target="_blank" is a one-liner
$('a.external').attr('target', '_blank');
// One great feature in jQuery is chainability (setters return
// themselves so we can call series of sets in chain)
// Select class="errorMessages" elements and do bunch of stuff to them
$('.errorMessages')
.css({'background' : '#d00', 'color' : '#fff'})
.opacity(0.8)
.addClass('someNewClassName')
.removeClass('removeSomeClassName')
.height('120px');
http://jsfiddle.net/hXXLh/3/
73. Perttu Myry 6.11.2012
JavaScript
jQuery
<html><body>
<div class="inputRow">Row #1: <input type="text" /> <span class=”button">Save</span></div>
<div class="inputRow">Row #2: <input type="text" /> <span class=”button">Save</span></div>
<!-- and so on... -->
</div>
</body></html>
<script type="text/javascript">
// could bind event listener to each row separately, but here it's more efficient to use event delegation
// which adds only one event listener to body and once click event bubbles up to body element,
// jQuery checks whether click originated from element that fits the given CSS selector
$(document.body).delegate('div.inputRow span:not(.disabled)', 'click', function(e) {
var span = $(this), input = $('input', span.parent());
span.addClass('disabled'); // disable save button when it is clicked for the first time
// do something with the data in this row...
doSave(input.value);
});
// delegate keyup event handler to catch all input keyup events in input row
$(document.body).delegate('div.inputRow input', 'keyup', function(e) {
// event is always found from e attribute regardless of browser
if(e.keyCode === 13) {
$('span.button', $(this).parent()).trigger('click');
}
});
</script>
http://jsfiddle.net/PhVpk/2/
74. Perttu Myry 6.11.2012
JavaScript
jQuery
// Animating with jQuery is a blast, get element id="infoBox",
// hide it immediately and reveal it during 0,5s animation
$('#infoBox').hide().show(500);
// Or get all class="openElement" elements in accordion
// and reveal their contents via 300ms slideDown animation
$('.accordion .openElement .content').slideDown(300);
// And AJAX is made also easy and flexible, check out api
$.ajax('http://www.somesite.com/news/rssfeed.php', {
success : function(data) {
// Update id="newsContainer" element's HTML content
$('#newsContainer').html(data);
},
error : function() {
$('#newsContainer').html('News feed is currently unavailable');
}
});
// Accordion example available at
http://jsfiddle.net/YzuLn/
75. Perttu Myry 6.11.2012
Modern Web Technologies
Table of Contents
JavaScript
CSS3
HTML5
Resources
76. Perttu Myry 6.11.2012
CSS3
Introduction
Introduction
Borders
Backgrounds
Colors and opacity
Shadows
Text and fonts
Selectors and media queries
Transitions and transforms
Tweaks
77. Perttu Myry 6.11.2012
CSS3
Introduction
“Cascading Style Sheets (CSS) is a style sheet
language used for describing the presentation
semantics (the look and formatting) of a
document written in a markup language.”
Wikipedia
CSS1 official recommendation published by W3C
in 1996 and CSS2 in 1998
Unlike previous recommendations, CSS3 consists of
modules which progress in different stages
Under constant development, some CSS3 features
can be used as defined in standard, some via
browser specific prefixes and some not at all
78. Perttu Myry 6.11.2012
CSS3
Introduction
Inorder to cover as much browsers as
possible, you often have to define set of
browser specific prefixes
CSS3 Please! provides good cross-browser
compatible CSS3 examples
Also some tools, such as Prefixr, can be
used to produce cross-browser
compatible code
CSS3 Cheat Sheet
79. Perttu Myry 6.11.2012
CSS3
Colors and opacity
Introduction
Colors and opacity
Borders
Backgrounds
Shadows
Text and fonts
Selectors and media queries
Transitions and transforms
Tweaks
80. Perttu Myry 6.11.2012
CSS3
Colors and opacity
CSS3 opacity can be used to define visibility
or transparency of an element
Value 0 means completely transparent
element is 1 completely visible element, 0.5
means 50% transparent element
IE versions 6-8 support this via filter, cross-
browser compatible code can be found from
CSS3 Please!
Setting opacity affects also descendant
elements’ opacity
81. Perttu Myry 6.11.2012
CSS3
Colors and opacity
If you want to create partially transparent
background and yet keep text completely
opaque, you can use rgba or hsla colors
Setting rbg(red, green, blue) colors works in all
major browsers, but rgba(red, green, blue, alpha)
is not supported by IE 6-8, for those you can go for
CSS-Tricks gradient workaround
Or if you want you can use 32-bit PNG images with
partial transparency in IE 7 and 8, but IE 6 fails to
show 32-bit PNG transparency, you could go for 8-
bit partial transparent PNG images, but only few
programs (not even Photoshop) are able to make
such files
82. Perttu Myry 6.11.2012
CSS3
Borders
Introduction
Colors and opacity
Borders
Backgrounds
Shadows
Text and fonts
Selectors and media queries
Transitions and transforms
Tweaks
83. Perttu Myry 6.11.2012
CSS3
Borders
CSS has had border support from version 1
CSS3 adds possibility to create better looking
borders via border-radius (rounded corners)
and border-image (use image as border)
Check out border-radius from CSS3 Please!
CSS-Tricks border-image tutorial
Example of border-image (this is the image
used in borders)
84. Perttu Myry 6.11.2012
CSS3
Backgrounds
Introduction
Colors and opacity
Borders
Backgrounds
Shadows
Text and fonts
Selectors and media queries
Transitions and transforms
Tweaks
85. Perttu Myry 6.11.2012
CSS3
Backgrounds
Similar to border, background has been part
of CSS since first version
CSS2 introduced possibility to define multiple
backgrounds separated by comma
CSS3 adds three new properties: background-
clip, background-origin and background-size
The last one is especially useful when making
background images cover the whole window
using background-size: cover
86. Perttu Myry 6.11.2012
CSS3
Backgrounds
Via CSS3 you don’t have to enter Photoshop
anymore in order to make gradients
Provides flexibility as colors are configurable in
CSS whereas in picture you’re stuck until you
update the picture
When combined with rgba colors, you can
create transparent gradients and just change
background-color in order to achieve easily
configurable color schemes
http://jsfiddle.net/xvxMH/1/
87. Perttu Myry 6.11.2012
CSS3
Backgrounds
Also faster because doesn’t need HTTP
request to fetch the background image
Still early draft so lots of different browser
prefixes are needed for cross-browser
support
Defining gradients is best done via such
tool as Ultimate CSS Gradient Generator
that provides you with CSS code you can
copy-paste in your CSS file
88. Perttu Myry 6.11.2012
CSS3
Shadows
Introduction
Colors and opacity
Borders
Backgrounds
Shadows
Text and fonts
Selectors and media queries
Transitions and transforms
Tweaks
89. Perttu Myry 6.11.2012
CSS3
Shadows
CSS3 has two shadow types which are box-
shadow (casts shadow to any element) and
text-shadow (casts shadow to text)
Shadows have four attributes: x-offset, y-
offset, radius (blur) and color
Box shadows can be drawn inside element
providing fifth attribute, keyword ”inset”
W3Schools box-shadow and text-shadow
references
http://jsfiddle.net/TJf6X/1/
90. Perttu Myry 6.11.2012
CSS3
Text and fonts
Introduction
Colors and opacity
Borders
Backgrounds
Shadows
Text and fonts
Selectors and media queries
Transitions and transforms
Tweaks
91. Perttu Myry 6.11.2012
CSS3
Text and fonts
CSS3 contains few useful properties when
working with text
In case element’s overflow is set to hidden,
text-overflow can be set to ellipsis to show ...
at the end of the clipped text
Another property, word-wrap, can be set to
break-word in order to allow adding line
break to unbreakable words (contains no
spaces or hyphens)
And property columns can be used to split
content into multiple columns
92. Perttu Myry 6.11.2012
CSS3
Text and fonts
But what really is the greatest text tool in CSS3
is web fonts via font-face property
Finally you can provide decent typography,
not just the same old web safe fonts
Via services like Google Web Fonts or Font
Squirrel adding custom fonts is easier and
more fun than ever before
If you do not find your pick from those or other
web services, you can create your own ones
http://jsfiddle.net/UN3YX/1/
93. Perttu Myry 6.11.2012
CSS3
Selectors and media queries
Introduction
Colors and opacity
Borders
Backgrounds
Shadows
Text and fonts
Selectors and media queries
Transitions and transforms
Tweaks
94. Perttu Myry 6.11.2012
CSS3
Selectors and media queries
CSS3 has powerful new selectors which can
be used to easily decorate your site or
application
W3Schools selector reference contains good
list and also states in which CSS version a
selector has been introduced to CSS
Especially attribute, such as a[src^="http"],
and nth-child(even|odd) selectors have
been proven very useful
http://jsfiddle.net/AaZzP/
95. Perttu Myry 6.11.2012
CSS3
Selectors and media queries
Yet another powerful concept introduced in
CSS3 are media queries
In CSS2 you can define different styles for
different media types, such as screen and
print
In CSS3 you can define new kind of rules
when styles apply or don’t apply
This enables responsive design that allows you
to use single code base for different platforms
and devices
96. Perttu Myry 6.11.2012
CSS3
Transitions and transforms
Introduction
Colors and opacity
Borders
Backgrounds
Shadows
Text and fonts
Selectors and media queries
Transitions and transforms
Tweaks
97. Perttu Myry 6.11.2012
CSS3
Transitions and transforms
Via transforms you can rotate, scale and skew
elements
On webkit browser you can also do 3D transforms
If browser supports CSS3 transitions, animating is as
easy as defining transition property to element
Again lots of browser prefixes exist so you can get
best outcome using CSS3 Please!
You can define what will be animated, in which
duration and using what kind of easing algorithm
98. Perttu Myry 6.11.2012
CSS3
Tweaks
Introduction
Colors and opacity
Borders
Backgrounds
Shadows
Text and fonts
Selectors and media queries
Transitions and transforms
Tweaks
99. Perttu Myry 6.11.2012
CSS3
Tweaks
Few more tweaks that might be useful
Box sizing example
Enable changing element size via resize
property
Setting border to element changes
element’s dimensions, this can be
avoided by using outline instead of
border
100. Perttu Myry 6.11.2012
Modern Web Technologies
Table of Contents
JavaScript
CSS3
HTML5
Resources
101. Perttu Myry 6.11.2012
HTML5
Introduction
Introduction
New elements and selectors
Audio and video
Web storage, web workers and web sockets
Geolocation
Drag and drop
File API
Notifications
Canvas
104. Perttu Myry 6.11.2012
HTML5
Introduction
Fifth revision of HTML markup language
Not yet completed standard
Predecessor HTML 4.01 standard not updated
since 2000
Started by Web Hypertext Application
Technology Working Group (WHATWG), now
joined by World Wide Web Consortium (W3C)
New standard adds new elements, removes
some old ones and adds new APIs
105. Perttu Myry 6.11.2012
HTML5
Introduction
Provides functionality that was previously
possible only via third party plug-ins, such
as Adobe Flash or Microsoft Silverlight
More advanced mathematically produced
graphics (SVG, canvas, CSS3)
Smooth animations
Video and audio playback
Socket connections (for example, possibility
to create highly performing chat without
having to poll for data using interval)
106. Perttu Myry 6.11.2012
HTML5
New elements and selectors
Introduction
New elements and selectors
Audio and video
Web storage, web workers and web sockets
Geolocation
Drag and drop
File API
Notifications
Canvas
107. Perttu Myry 6.11.2012
HTML5
New elements and selectors
More detailed information in W3Schools HTML5
Tutorial
Semantic elements: article, aside, bdi, command,
details, summary, figure, figcaption, footer, header,
hgroup, mark, meter, nav, progress, ruby, rt, rp,
section, time, wbr
Media elements: audio, video, source, embed, track
Canvas element: canvas
Form elements: datalist, keygen, output
Removed elements: acronym, applet, basefont, big,
center, dir, font, frame, frameset, noframes, strike, tt,
u
http://jsfiddle.net/Vd7Y7/
108. Perttu Myry 6.11.2012
HTML5
New elements and selectors
New <input> types: color, date, datetime,
datetime-local, email, month, number, range,
search, tel, time, url, week
New <form> attributes: autocomplete, novalidate
New <input> attributes: autocomplete, autofocus,
form, formaction, formenctype, formmethod,
formnovalidate, formtarget, height and width, list,
min and max, multiple, pattern (regexp),
placeholder, required, step
New selectors: getElementsByClassName,
querySelector and querySelectorAll
HTML5 Cheat Sheet
109. Perttu Myry 6.11.2012
HTML5
Audio and video
Introduction
New elements and selectors
Audio and video
Web storage, web workers and web sockets
Geolocation
Drag and drop
File API
Notifications
Canvas
110. Perttu Myry 6.11.2012
HTML5
Audio and video
Possibility to embed sound via <audio> tag
and video by <video> tag
Supported by all major browsers
Content written inside <audio> or <video> tag
will be used as fallback in non-supported
environments
This provides excellent possibility to use HTML5
if possible, fallback to Flash (or some other
third-party technology) in older browsers or
finally fallback to show some error message in
completely non-supported environments
111. Perttu Myry 6.11.2012
HTML5
Audio and video
HTML attributes
controls : Displays the standard HTML5 controls for the
audio on the web page
autoplay : Makes the content play automatically
loop : Make the content repeat (loop) automatically
DOM methods
play(): Play the audio/video
pause(): Pause the playback
load(): Load new source to player
canPlayType(): Check whether browser can playback
certain audio or video format (such as ”video/mp4” or
”audio/mp3”)
112. Perttu Myry 6.11.2012
HTML5
Audio and video
DOM properties
currentSrc, currentTime, videoWidth,
videoHeight, duration, ended, error,
paused, muted, seeking, volume, height,
width
DOM events
play, pause, progress, error, timeupdate,
ended, abort, empty, emptied, waiting,
loadedmetadata
113. Perttu Myry 6.11.2012
HTML5
Audio and video
Testing <audio> tag
Testing <video> tag
<video> with custom controls
And to make life even easier, you can use
third party players like JW Player or jPlayer
HTML5 and automatic fallback to Flash
Consistent API in all browsers regardless
HTML5 or Flash is used
114. Perttu Myry 6.11.2012
HTML5
Web storage, web workers and web sockets
Introduction
New elements and selectors
Audio and video
Web storage, web workers and web sockets
Geolocation
Drag and drop
File API
Notifications
Canvas
115. Perttu Myry 6.11.2012
HTML5
Web storage, web workers and web sockets
Web storage provides possibility to store data
locally into browser
localStorage: permanent data storage
sessionStorage: temporary data storage, data is
cleared when session dies (when browser
window/tab is closed, depends on browser
implementation)
No more cookies! Supported by all major browsers
Via feature detection it is possible to create such
functionality that will use localStorage if available
or fallback to cookies (old IE < 8)
http://jsfiddle.net/MjZrj/1/
116. Perttu Myry 6.11.2012
HTML5
Web storage, web workers and web sockets
Web workers can be used to execute
resource heavy JavaScript calculations in
the background without interrupting UI
http://slides.html5rocks.com/#web-
workers
117. Perttu Myry 6.11.2012
HTML5
Web storage, web workers and web sockets
// Code examples from
http://www.html5rocks.com/en/tutorials/workers/basics/
// Main script
var worker = new Worker('doWork.js');
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
}, false);
worker.postMessage('Hello World'); // Send data to our worker.
// doWork.js (the worker):
self.addEventListener('message', function(e) {
self.postMessage(e.data);
}, false);
118. Perttu Myry 6.11.2012
HTML5
Web storage, web workers and web sockets
”WebSockets is a technique for two-way
communication over one (TCP) socket, a
type of PUSH technology. At the moment,
it’s still being standardized by the W3C;
however, the latest versions of Chrome
and Safari have support for WebSockets.”
http://net.tutsplus.com/tutorials/javascript
-ajax/start-using-html5-websockets-today/
119. Perttu Myry 6.11.2012
HTML5
Web storage, web workers and web sockets
Pushing data to client can also be achieved
by technique called long polling
Client sends HTTP request to server, but server
does not send response until certain timeout is
reached or it has some data to respond
Once client received response, it immediately
fires up new ”long poll” HTTP request
This way there is always one connection live
between client and server
120. Perttu Myry 6.11.2012
HTML5
Web storage, web workers and web sockets
In some environments socket connections can be
blocked by firewalls depending on what port is
used for the socket connection
Sometimes can be solved by routing
Configure two different IP addresses, A for normal
HTTP requests and B for socket connections
Make socket connections to B port 80 and route
connection to some custom port on A
This solution can also cause problems, advanced
firewalls can detect request containing non-HTTP
traffic to port 80 and again block the request
121. Perttu Myry 6.11.2012
HTML5
Web storage, web workers and web sockets
At the moment these slides were created, only
Firefox, Chrome and Safari supported sockets, if
this is not an issue and firewalls are not a problem
in your case, go for sockets
Strips away HTTP headers and therefore requires
less bandwidth
Also handling socket connections can be done by
some really light weight server side
implementation, such as something created using
Node.js
This can provide really well performing
connections
http://slides.html5rocks.com/#web-sockets
122. Perttu Myry 6.11.2012
HTML5
Web storage, web workers and web sockets
Don’t try to reinvent the wheel by yourself,
there are several third-party tools to help
you out
One excellent option is Socket.IO
Based on Node.js
Provides fallbacks which makes it
compatible with practically every browser
No personal experience, but based on
”how to use” examples looks very simple
and lightweight
123. Perttu Myry 6.11.2012
HTML5
Geolocation
Introduction
New elements and selectors
Audio and video
Web storage, web workers and web sockets
Geolocation
Drag and drop
File API
Notifications
Canvas
124. Perttu Myry 6.11.2012
HTML5
Geolocation
Can be used to locate user via
GPS
A-GPS (assistive GPS, triangulation between mobile
phone towers and public masts)
Wi-Fi hotspots
IP address ranges
User is prompted for permission per domain
Browsers will remember the decision if not
bypassed or specifically changed later in browser
settings by user
http://www.w3.org/TR/geolocation-API/#security
125. Perttu Myry 6.11.2012
HTML5
Geolocation
// Function showMap is used to handle successful get position
function showMap(position) {
// Position has coords property which furthermore has
// properties latitude, longitude, altitude, accuracy,
// altitudeAccuracy, heading and speed
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var map = new google.maps.Map($("#myMap").get(0), {
zoom: 12,
center: new google.maps.LatLng(lat, lon),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
// Availability can be checked via navigator.geolocation property
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showMap);
}
http://jsfiddle.net/H4RtF/2/
http://jsfiddle.net/H4RtF/2/embedded/result/
126. Perttu Myry 6.11.2012
HTML5
Drag and drop
Introduction
New elements and selectors
Audio and video
Web storage, web workers and web sockets
Geolocation
Drag and drop
File API
Notifications
Canvas
127. Perttu Myry 6.11.2012
HTML5
Drag and drop
Arguably the worst part of HTML5
specification
”No one will argue that HTML5's DnD model is
complicated compared to other solutions like
JQuery UI.”
HTML5 Rocks DnD tutorial
Seams easy at the beginning, just add
draggable=”true” to any element you want
to drag
This just makes elements draggable, you
cannot drop them anywhere
128. Perttu Myry 6.11.2012
HTML5
Drag and drop
Adding some functionality into dragging can be
achieved via seven events which are dragstart,
drag, dragenter, dragleave, dragover, drop and
dragend
There are differences in how different browsers
have implemented these events
In dragover event handler default action needs to
be prevented in order to enable dropping
DnD ”magic” happens in event’s DataTransfer
object
HTML5 Rocks tutorial covers this topic well
129. Perttu Myry 6.11.2012
HTML5
File API
Introduction
New elements and selectors
Audio and video
Web storage, web workers and web sockets
Geolocation
Drag and drop
File API
Notifications
Canvas
130. Perttu Myry 6.11.2012
HTML5
File API
Provides functionality to let user select files,
read content of those files and then use them
directly or upload them to server
Files can be selected either via <input
type=”file”> or by dragging them from file
system to browser window
In case <input> is used, ”change” event
listener needs to be bind to the input
In case drag and drop is used, check out how
DnD works in previous chapters few slides
back
131. Perttu Myry 6.11.2012
HTML5
File API
Simple file DnD (drag and drop) demo
http://html5demos.com/file-api
Good tutorial with nice examples
http://www.html5rocks.com/en/tutorials/fi
le/dndfiles/
Upload images using DnD and service
automatically resizes and provides
different size versions of uploaded images
http://imgscalr.com/
132. Perttu Myry 6.11.2012
HTML5
Notifications
Introduction
New elements and selectors
Audio and video
Web storage, web workers and web sockets
Geolocation
File API
Drag and drop
Notifications
Canvas
133. Perttu Myry 6.11.2012
HTML5
Notifications
Not actually part of any standard, but worth
mentioning here
Only webkit currently supports notifications
Can be used to show notifications to user
outside the browser window (if user allows
notifications, compare to geolocation)
Works even if browser window is minimized
Again, HTML5 Rocks tutorial covers this well
134. Perttu Myry 6.11.2012
HTML5
Canvas
Introduction
New elements and selectors
Audio and video
Web storage, web workers and web sockets
Geolocation
File API
Drag and drop
Notifications
Canvas
135. Perttu Myry 6.11.2012
HTML5
Canvas
Canvas element can be used to draw graphics
programmatically
Has only two attributes, width and height, which
are both optional and can be set using DOM
properties
Similar to <audio> and <video> elements, fallback
content can be written <canvas>inside canvas
element</canvas>
Drawing into canvas can be done via rendering
context that can currently be 2D for most browsers
and also 3D for browsers that support WebGL
IE 9 supports canvas, for older versions of IE
ExplorerCanvas can be used
137. Perttu Myry 6.11.2012
HTML5
Canvas
3D examples
3D picture wall
Canvascape
How to create particle system using
Three.js
CanvasMol
Quake 2 ported to HTML5 (Youtube)
Collection of 10 WebGL examples
138. Perttu Myry 6.11.2012
Modern Web Technologies
Table of Contents
JavaScript
HTML5
CSS3
Resources
139. Perttu Myry 6.11.2012
Resources
Books
Secrets of the JavaScript Ninja
Unpublished yet, have been reading the early
access version and learned a lot
Author John Resig is the creator and lead
developer of jQuery
Head First Design Patterns
Learned lot of good practices from this book
Design patterns can be used to enhance
architecture regardless of programming
language used
Getting Real
Good book about web-based application
development
144. Perttu Myry 6.11.2012
Resources
Notes
Example covering use of JSON in sending
and receiving data in AJAX requests
http://jsfiddle.net/gMG5c/2/
AJAX news feed example
http://jsfiddle.net/q3sEC/8/
JavaScript encrypt and decrypt example
http://jsfiddle.net/G5RWa/