• Save
Modern Web Technologies
Upcoming SlideShare
Loading in...5
×
 

Modern Web Technologies

on

  • 9,025 views

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. ...

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.

Statistics

Views

Total Views
9,025
Views on SlideShare
8,438
Embed Views
587

Actions

Likes
13
Downloads
0
Comments
3

28 Embeds 587

http://webplog.blogspot.com 219
http://webplog.blogspot.fi 120
http://webplog.blogspot.ru 98
http://webplog.blogspot.hk 34
http://webplog.blogspot.de 23
http://webplog.blogspot.in 22
http://webplog.blogspot.co.uk 20
http://webplog.blogspot.tw 7
http://webplog.blogspot.hu 5
http://webplog.blogspot.com.br 5
http://webplog.blogspot.mx 4
http://webplog.blogspot.fr 4
http://translate.googleusercontent.com 3
http://webplog.blogspot.com.es 3
http://webplog.blogspot.jp 3
http://webplog.blogspot.ae 2
http://webplog.blogspot.ca 2
http://localhost 2
http://webplog.blogspot.it 2
http://webplog.blogspot.gr 1
http://webplog.blogspot.ie 1
http://webplog.blogspot.pt 1
http://webplog.blogspot.se 1
http://webplog.blogspot.dk 1
http://webplog.blogspot.com.au 1
http://webplog.blogspot.ro 1
http://webplog.blogspot.no 1
http://webplog.blogspot.be 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

13 of 3 Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • Today during the lecture some questions popped up about JavaScript cryptography when I was talking about HTML5 localStorage. I made a simple example how to utilize Crypto-JS library to encrypt an decrypt content. This way you could store encrypted content to localStorage which could be decrypted only by using correct passphrase. This example is available at http://jsfiddle.net/G5RWa/ and this link was added also to the last slide of the presentation.
    Are you sure you want to
    Your message goes here
    Processing…
  • While giving a lecture at JAMK University of Applied Sciences students were asking about JavaScript debugging. I think it fits well into the slides so I added a brief section about debugging before going into jQuery. It's rather simple, but covers some basics which I've found rather useful in web development.

    Tomorrow I'm going to continue about CSS3 and HTML5 at JAMK and I quickly revised those slides. WebGL support has been extended since I created these slides so WebGL is not introduced as webkit specific feature anymore.
    Are you sure you want to
    Your message goes here
    Processing…
  • I revised these slides and made some minor modifications. CSS3 section is now introduced before HTML5, JavaScript singleton pattern usage is consistent and I added few slides about cross-domain AJAX requests utilizing JSONP technique.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Modern Web Technologies Modern Web Technologies Presentation Transcript

    • Perttu Myry 6.11.2012Modern WebTechnologiesJavaScript, CSS3 and HTML5
    • Perttu Myry 6.11.2012Modern Web TechnologiesTable of Contents JavaScript CSS3 HTML5 Resources
    • Perttu Myry 6.11.2012JavaScriptIntroduction Introduction DOM Events and Feature Detection AJAX and JSON Animations Object-Oriented JavaScript Unobtrusive JavaScript Debugging jQuery
    • Perttu Myry 6.11.2012JavaScriptIntroduction 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
    • Perttu Myry 6.11.2012JavaScriptIntroduction 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
    • Perttu Myry 6.11.2012JavaScriptIntroduction<!-- 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>
    • Perttu Myry 6.11.2012JavaScriptIntroduction// 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 notationwindow.title = some string;// Setting object property via square bracket notationwindow[title] = some string;function doSomething() { // Variable without var statement makes it // always global regardless of scope title = some string;}doSomething();
    • Perttu Myry 6.11.2012JavaScriptIntroduction// Two popular ways of writing functions in JavaScript// Traditional way to write a functionfunction 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 variablevar doSomething = function(someAttribute) { // Do something here...}// Executing function...doSomething(some value);
    • Perttu Myry 6.11.2012JavaScriptDOM Introduction DOM Events and Feature Detection AJAX and JSON Animations Object-Oriented JavaScript Unobtrusive JavaScript Debugging jQuery
    • 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
    • Perttu Myry 6.11.2012JavaScriptDOM “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
    • Perttu Myry 6.11.2012JavaScriptDOM 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()
    • Perttu Myry 6.11.2012JavaScriptDOM<!-- 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);// wrappers 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/
    • Perttu Myry 6.11.2012JavaScriptDOM 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 isnt very flexible option either Lets take a look at CSS selectors
    • Perttu Myry 6.11.2012JavaScriptDOM<!-- 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.htmlalert(document.getElementsByTagName(a)[0].href);// modern browser support native CSS selectorsif(document.querySelectorAll) { // find all anchors which have class name external // alerts http://www.google.fi/ alert(document.querySelectorAll(a.external)[0].href);}</script>
    • Perttu Myry 6.11.2012JavaScriptDOM<!-- 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, lets use JavaScript to make// HTML code valid and yet class="external" links open in new browser window/tabif(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/
    • Perttu Myry 6.11.2012JavaScriptEvents and Feature Detection Introduction DOM Events and Feature Detection AJAX and JSON Animations Object-Oriented JavaScript Unobtrusive JavaScript Debugging jQuery
    • Perttu Myry 6.11.2012JavaScriptEvents 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
    • Perttu Myry 6.11.2012JavaScriptEvents and Feature Detection
    • Perttu Myry 6.11.2012JavaScriptEvents 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 fnvar 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>
    • Perttu Myry 6.11.2012JavaScriptEvents 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
    • Perttu Myry 6.11.2012JavaScriptEvents 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);}));
    • Perttu Myry 6.11.2012JavaScriptEvents 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?
    • Perttu Myry 6.11.2012JavaScriptEvents and Feature Detection// Fixed example using feature detection that works in "all" browsersfunction 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 dont support old browsers alert(Sorry, this application does not support old browsers); }}
    • Perttu Myry 6.11.2012JavaScriptEvents and Feature Detection// Usage examplesbind(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(); }});
    • Perttu Myry 6.11.2012JavaScriptEvents and Feature Detection// Event triggeringfunction 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); }}
    • Perttu Myry 6.11.2012JavaScriptEvents 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...
    • Perttu Myry 6.11.2012JavaScriptEvents and Feature Detectionvar 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/
    • Perttu Myry 6.11.2012JavaScriptAJAX and JSON Introduction DOM Events and Feature Detection AJAX and JSON Animations Object-Oriented JavaScript Unobtrusive JavaScript Debugging jQuery
    • Perttu Myry 6.11.2012JavaScriptAJAX 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
    • Perttu Myry 6.11.2012JavaScriptAJAX 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
    • Perttu Myry 6.11.2012JavaScriptAJAX and JSONfunction 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();}
    • Perttu Myry 6.11.2012JavaScriptAJAX 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);});
    • Perttu Myry 6.11.2012JavaScriptAJAX 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
    • Perttu Myry 6.11.2012JavaScriptAJAX and JSON<!-- Modern browsers have built-in support for JSON via global JSONobject, 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 stringvar jsonString = JSON.stringify(myObject);// Convert JSON string back to JavaScript objectvar myObject = JSON.parse(jsonString);</script>
    • Perttu Myry 6.11.2012JavaScriptAJAX 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/
    • Perttu Myry 6.11.2012JavaScriptAJAX 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
    • Perttu Myry 6.11.2012JavaScriptAJAX and JSON<!-- JSONP technique exploits script tag which is not restricted to samedomain policy as XMLHttpRequest is --><script type="text/javascript">// Define callback functionfunction myCallbackFunction(json) { // do something with json data here...};// Create script elementvar 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 headdocument.getElementsByTagName(head)[0].appendChild(scriptTag);</script>
    • Perttu Myry 6.11.2012JavaScriptAnimations Introduction DOM Events and Feature Detection AJAX and JSON Animations Object-Oriented JavaScript Unobtrusive JavaScript Debugging jQuery
    • Perttu Myry 6.11.2012JavaScriptAnimations 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
    • Perttu Myry 6.11.2012JavaScriptAnimations 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
    • Perttu Myry 6.11.2012JavaScriptAnimations<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 stopsetTimeout(moveBox, 100);// setInterval will call function again and again, box will move// 5 pixels to every 20th millisecondsetInterval(moveBox, 20);</script>http://jsfiddle.net/rk4fH/1/
    • Perttu Myry 6.11.2012JavaScriptAnimations 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
    • Perttu Myry 6.11.2012JavaScriptAnimations// Lets do bit different version of moveBox functionfunction 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/
    • Perttu Myry 6.11.2012JavaScriptAnimations 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
    • Perttu Myry 6.11.2012JavaScriptObject-Oriented JavaScript Introduction DOM Events and Feature Detection AJAX and JSON Animations Object-Oriented JavaScript Unobtrusive JavaScript Debugging jQuery
    • Perttu Myry 6.11.2012JavaScriptObject-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
    • Perttu Myry 6.11.2012JavaScriptObject-Oriented JavaScript// Define a new class Carfunction 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; };}
    • Perttu Myry 6.11.2012JavaScriptObject-Oriented JavaScript// Create new Carvar ford = new Car(Ford);alert(ford.model); // Alerts "Ford"alert(ford.getColor()); // Alerts "Red" (default)ford.setColor(Blue); // Change ford coloralert(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);
    • Perttu Myry 6.11.2012JavaScriptObject-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 Its crucial to understand the difference of copying a function compared to referring to a function Can be affected via call or apply functions
    • Perttu Myry 6.11.2012JavaScriptObject-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; // truehighlight(); // causes error, because window.style is undefined// copy function to onmouseoverdocument.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>
    • Perttu Myry 6.11.2012JavaScriptObject-Oriented JavaScript// OOP example of how keyword this can be misusedvar Person = function(nickname) { this.nickname = nickname;};// New methods to classes can be introduced via prototypePerson.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 objectsayJohnName(); // Alerts undefined// Function call or apply can be used to define where "this" pointssayJohnName.call(john); // Alerts "John"sayJohnName.call(jane); // Alerts "Jane"
    • Perttu Myry 6.11.2012JavaScriptObject-Oriented JavaScript// Singleton pattern in JavaScript suggested by Douglas Crockfordvar 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 returnsCarFactory.createCar(Ford);CarFactory.createCar(Dodge);CarFactory.createCar(Hyundai);CarFactory.countCreatedModels(); // Alerts 3CarFactory.alertCreatedModels(); // Alerts "Ford, Dodge, Hyundai"
    • Perttu Myry 6.11.2012JavaScriptUnobtrusive JavaScript Introduction DOM Events and Feature Detection AJAX and JSON Animations Object-Oriented JavaScript Unobtrusive JavaScript Debugging jQuery
    • Perttu Myry 6.11.2012JavaScriptUnobtrusive 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
    • Perttu Myry 6.11.2012JavaScriptUnobtrusive JavaScript<!-- Old school ugly way to write JavaScript --><a href="javascript:fetchNews();">Show 10 latest news</a><script type="text/javascript">// introducing global function fetchNewsfunction fetchNews() { // fetch 10 latest news here using AJAX...};</script>
    • Perttu Myry 6.11.2012JavaScriptUnobtrusive JavaScript<!-- Better in terms of decoupling plus does not introduce newglobal function fetchNews, but this does nothing if JavaScriptsupport 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>
    • Perttu Myry 6.11.2012JavaScriptUnobtrusive JavaScript<!-- Proper unobtrusive way is to provide fallback. Now ifJavaScript is enabled system will fetch news using AJAX,but in JavaScript disabled environments browser will openlatestNews.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>
    • Perttu Myry 6.11.2012JavaScriptUnobtrusive 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 functionalityfunction 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?
    • Perttu Myry 6.11.2012JavaScriptUnobtrusive JavaScript// Use namespacing and singleton patternvar 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...
    • Perttu Myry 6.11.2012JavaScriptUnobtrusive 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 indentationCustomCars.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/
    • Perttu Myry 6.11.2012JavaScriptDebugging Introduction DOM Events and Feature Detection Unobtrusive JavaScript AJAX and JSON Animations Object-Oriented JavaScript Debugging jQuery
    • Perttu Myry 6.11.2012JavaScriptDebugging 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
    • Perttu Myry 6.11.2012JavaScriptDebugging 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
    • Perttu Myry 6.11.2012JavaScriptDebugging// Console grouping and loggingconsole.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/
    • Perttu Myry 6.11.2012JavaScriptDebugging 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/
    • Perttu Myry 6.11.2012JavaScriptjQuery Introduction DOM Events and Feature Detection Unobtrusive JavaScript AJAX and JSON Animations Object-Oriented JavaScript Debugging jQuery
    • Perttu Myry 6.11.2012JavaScriptjQuery 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
    • Perttu Myry 6.11.2012JavaScriptjQuery gs.statcounter.com
    • Perttu Myry 6.11.2012JavaScriptjQuery ”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
    • Perttu Myry 6.11.2012JavaScriptjQuery 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
    • Perttu Myry 6.11.2012JavaScriptjQuery// jQuery and its CSS selectors can be used via global variable $// (or jQuery), lets take a look at some new and previous// examples how to use jQuery// alerts how many external anchors there are on the pagealert(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/
    • Perttu Myry 6.11.2012JavaScriptjQuery<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 its 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/
    • Perttu Myry 6.11.2012JavaScriptjQuery// 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" elements HTML content $(#newsContainer).html(data); }, error : function() { $(#newsContainer).html(News feed is currently unavailable); }});// Accordion example available athttp://jsfiddle.net/YzuLn/
    • Perttu Myry 6.11.2012Modern Web TechnologiesTable of Contents JavaScript CSS3 HTML5 Resources
    • Perttu Myry 6.11.2012CSS3Introduction Introduction Borders Backgrounds Colors and opacity Shadows Text and fonts Selectors and media queries Transitions and transforms Tweaks
    • Perttu Myry 6.11.2012CSS3Introduction “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
    • Perttu Myry 6.11.2012CSS3Introduction 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
    • Perttu Myry 6.11.2012CSS3Colors and opacity Introduction Colors and opacity Borders Backgrounds Shadows Text and fonts Selectors and media queries Transitions and transforms Tweaks
    • Perttu Myry 6.11.2012CSS3Colors 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
    • Perttu Myry 6.11.2012CSS3Colors 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
    • Perttu Myry 6.11.2012CSS3Borders Introduction Colors and opacity Borders Backgrounds Shadows Text and fonts Selectors and media queries Transitions and transforms Tweaks
    • Perttu Myry 6.11.2012CSS3Borders 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)
    • Perttu Myry 6.11.2012CSS3Backgrounds Introduction Colors and opacity Borders Backgrounds Shadows Text and fonts Selectors and media queries Transitions and transforms Tweaks
    • Perttu Myry 6.11.2012CSS3Backgrounds 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
    • Perttu Myry 6.11.2012CSS3Backgrounds 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/
    • Perttu Myry 6.11.2012CSS3Backgrounds 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
    • Perttu Myry 6.11.2012CSS3Shadows Introduction Colors and opacity Borders Backgrounds Shadows Text and fonts Selectors and media queries Transitions and transforms Tweaks
    • Perttu Myry 6.11.2012CSS3Shadows 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/
    • Perttu Myry 6.11.2012CSS3Text and fonts Introduction Colors and opacity Borders Backgrounds Shadows Text and fonts Selectors and media queries Transitions and transforms Tweaks
    • Perttu Myry 6.11.2012CSS3Text 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
    • Perttu Myry 6.11.2012CSS3Text 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/
    • Perttu Myry 6.11.2012CSS3Selectors and media queries Introduction Colors and opacity Borders Backgrounds Shadows Text and fonts Selectors and media queries Transitions and transforms Tweaks
    • Perttu Myry 6.11.2012CSS3Selectors 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/
    • Perttu Myry 6.11.2012CSS3Selectors 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
    • Perttu Myry 6.11.2012CSS3Transitions and transforms Introduction Colors and opacity Borders Backgrounds Shadows Text and fonts Selectors and media queries Transitions and transforms Tweaks
    • Perttu Myry 6.11.2012CSS3Transitions 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
    • Perttu Myry 6.11.2012CSS3Tweaks Introduction Colors and opacity Borders Backgrounds Shadows Text and fonts Selectors and media queries Transitions and transforms Tweaks
    • Perttu Myry 6.11.2012CSS3Tweaks 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
    • Perttu Myry 6.11.2012Modern Web TechnologiesTable of Contents JavaScript CSS3 HTML5 Resources
    • Perttu Myry 6.11.2012HTML5Introduction Introduction New elements and selectors Audio and video Web storage, web workers and web sockets Geolocation Drag and drop File API Notifications Canvas
    • Perttu Myry 6.11.2012HTML5 SemanticsIntroduction Offline & Storage Device Access Connectivity Multimedia 3D, Graphics and Effects Performance and Integration CSS3 http://www.w3.org/html/logo/#the-technology
    • Perttu Myry 6.11.2012HTML5Introduction
    • Perttu Myry 6.11.2012HTML5Introduction 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
    • Perttu Myry 6.11.2012HTML5Introduction 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)
    • Perttu Myry 6.11.2012HTML5New 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
    • Perttu Myry 6.11.2012HTML5New 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/
    • Perttu Myry 6.11.2012HTML5New 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
    • Perttu Myry 6.11.2012HTML5Audio 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
    • Perttu Myry 6.11.2012HTML5Audio 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
    • Perttu Myry 6.11.2012HTML5Audio 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”)
    • Perttu Myry 6.11.2012HTML5Audio 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
    • Perttu Myry 6.11.2012HTML5Audio 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
    • Perttu Myry 6.11.2012HTML5Web 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
    • Perttu Myry 6.11.2012HTML5Web 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/
    • Perttu Myry 6.11.2012HTML5Web 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
    • Perttu Myry 6.11.2012HTML5Web storage, web workers and web sockets// Code examples fromhttp://www.html5rocks.com/en/tutorials/workers/basics/// Main scriptvar 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);
    • Perttu Myry 6.11.2012HTML5Web 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/
    • Perttu Myry 6.11.2012HTML5Web 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
    • Perttu Myry 6.11.2012HTML5Web 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
    • Perttu Myry 6.11.2012HTML5Web 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
    • Perttu Myry 6.11.2012HTML5Web 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
    • Perttu Myry 6.11.2012HTML5Geolocation Introduction New elements and selectors Audio and video Web storage, web workers and web sockets Geolocation Drag and drop File API Notifications Canvas
    • Perttu Myry 6.11.2012HTML5Geolocation 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
    • Perttu Myry 6.11.2012HTML5Geolocation// Function showMap is used to handle successful get positionfunction 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 propertyif(navigator.geolocation) { navigator.geolocation.getCurrentPosition(showMap);}http://jsfiddle.net/H4RtF/2/http://jsfiddle.net/H4RtF/2/embedded/result/
    • Perttu Myry 6.11.2012HTML5Drag 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
    • Perttu Myry 6.11.2012HTML5Drag and drop Arguably the worst part of HTML5 specification ”No one will argue that HTML5s 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
    • Perttu Myry 6.11.2012HTML5Drag 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
    • Perttu Myry 6.11.2012HTML5File API Introduction New elements and selectors Audio and video Web storage, web workers and web sockets Geolocation Drag and drop File API Notifications Canvas
    • Perttu Myry 6.11.2012HTML5File 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
    • Perttu Myry 6.11.2012HTML5File 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/
    • Perttu Myry 6.11.2012HTML5Notifications Introduction New elements and selectors Audio and video Web storage, web workers and web sockets Geolocation File API Drag and drop Notifications Canvas
    • Perttu Myry 6.11.2012HTML5Notifications 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
    • Perttu Myry 6.11.2012HTML5Canvas Introduction New elements and selectors Audio and video Web storage, web workers and web sockets Geolocation File API Drag and drop Notifications Canvas
    • Perttu Myry 6.11.2012HTML5Canvas 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
    • Perttu Myry 6.11.2012HTML5Canvas 2D examples Canvas 2D context methods and properties W3Schools simple demo Flash killer Video particles Biolab Disaster Collection of 15 examples
    • Perttu Myry 6.11.2012HTML5Canvas 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
    • Perttu Myry 6.11.2012Modern Web TechnologiesTable of Contents JavaScript HTML5 CSS3 Resources
    • Perttu Myry 6.11.2012ResourcesBooks 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
    • Perttu Myry 6.11.2012ResourcesLinks General  http://jsfiddle.net/  http://snook.ca/  http://css-tricks.com/  http://hacks.mozilla.org/  https://developer.mozilla.org/  http://www.w3schools.com/  http://gs.statcounter.com/  HTML5 & CSS3 Browser Support  Modernizr
    • Perttu Myry 6.11.2012ResourcesLinks JavaScript  http://blog.stevensanderson.com/2010/07/05/in troducing-knockout-a-ui-library-for-javascript/  http://stackoverflow.com/questions/2716069/ho w-does-this-javascript-jquery-syntax-work- function-window-undefined  http://jonraasch.com/blog/10-javascript- performance-boosting-tips-from-nicholas-zakas  http://developer.yahoo.com/performance/rule s.html  http://www.w3schools.com/jquery/default.asp
    • Perttu Myry 6.11.2012ResourcesLinks CSS  http://meyerweb.com/eric/tools/css/reset/  http://css3please.com/  http://www.colorzilla.com/gradient-editor/  http://www.fontsquirrel.com/  http://www.google.com/webfonts  http://www.css3.info/
    • Perttu Myry 6.11.2012ResourcesLinks HTML5  http://slides.html5rocks.com/  http://html5rocks.com/  http://html5demos.com/  http://www.html5canvastutorials.com/
    • Perttu Myry 6.11.2012ResourcesNotes 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/