IP492F15A

From CourseWiki

(Redirected from IP492)
Jump to: navigation, search

HTML5 3: Building Dynamic Experiences with JavaScript

Register for this course: HTML5 3: Building Dynamic Experiences with JavaScript

Course Description

This course can be applied to the UBC HTML5 Academy

HTML5 offers new and enhanced capabilities that were previously unattainable or difficult to implement in HTML4. To access these you need JavaScript. In this course you will learn to use JavaScript to implement these HTML5 features on your web site:

  • contenteditable
  • Drag & Drop
  • Canvas
  • Form Elements
  • Web Storage
  • Application Caching
  • Geolocation

Course Duration: 12 Hours (4 evenings)

Prerequisites:
Fundamentals of HTML5 2: (IP491)
JavaScript Introduction (IP356)


Register for this course

Theoretical Objectives

At the end of the course you will be able to discuss or answer: What are the new dynamic features of HTML5?
  • Editable
  • Drag & Drop
  • Canvas
    • applications
  • Form Elements
    • front-end impacts
    • back-end considerations
  • Web Storage
    • what does this replace
    • applications
  • Application Caching
    • considerations
  • Geolocation
    • integration with web services

Practical Objectives

You will learn about creating standards compliant web sites and apply the Theoretical Objectives to use these new elements in your web pages

  • Editable
  • Drag & Drop
  • Canvas to create dynamic graphic elements
  • Form Elements for data validation
  • Web Storage for offline data retention
  • Application Caching for offline application availability
  • Geolocation for enhancing the user experience

Prerequisites

Access to the internet is required to complete assignments.

Computer Equipment

The sessions are conducted in a computer lab, and you will have a computer provided for your use. You are welcome to bring your own computer to the lab sessions if you prefer to use that. Wireless access is available in the lab.

Please note that at times you will be doing a fair bit of typing and you will want to have a large enough screen and separate physical keyboard so that you can view content and type at the same time.

If it appears that you are having challenges with your own device, we will ask you to use the computer provided for you in the lab.

Storage

Please plan to use your own cloud based storage SkyDrive, DropBox, iCloud (or similar) or a USB storage key.

Instructional Methods

  • Hands-on labs
  • Discussion
  • Online collaboration
  • Homework assignments submitted online
  • Lecture

Course Materials

  • Web site
  • Course notes
  • Printed copies of on-screen lecture notes available on request during lectures

No Recording or Pictures in the Lab

Please note: Taking pictures or video during the course sessions is not permitted. All the course materials and lecture notes are available in physical form and on the web.


Requirements for Completion
  • Attend all sessions
  • Participate in class workshops with others (pairs and small group work)
  • Complete assignments: Typically this involves:
    • Blog for this session Join the conversation.
    • Creating web pages that use concepts introduced each week. (Apply)
    • Questions and Answers in PeerWise: (Recall)
      • Create questions online: minimum 1 per week - due by midnight Mondays
      • Answer all unanswered questions online: minimum 5 per week - due by 5:00 pm Tuesdays

See tabs for each week.


HTML 5

Coming Soon
Courses coming

Follow JimUBC on Twitter for latest course updates
Follow JimUBC on Twitter for latest course updates

Contents


Session One

Samples and Demos

Demo site


Blog for this session Join the conversation. Join the conversation.

  • Peerwise
  • Peerwise Course ID: 12329
  • Course Identifier IP492F15A
  • Students *


Things to do right away
Set up Development Platform
  • OR enter the settings manually

  • Create a student template upon which you can build your explorations and assignments

Register for this course

  • Sessions: 4 Tuesdays - November 24 — December 15, 2015 6:30pm - 9:30pm
  • Location: Lab C460
  • Students: 5 *
  • Course Assistant: Mandy Lui



Course Evaluation Form



Session One

This session is all about JavaScript
  • Because it is the glue that allows us to bring all the other pieces of the modern web experience together.
  • Because so many of the aspects of HTML5 require JavaScript to bring them to life.
After this session you will be able to
  • Discuss the relationship between HTML5, CSS and JavaScript
In preparation for using JavaScript in HTML5 you will
  • Use Strict Mode "use strict";
  • Understand the various options for where you place your JavaScript within a page
    • <head>, inline in the <body> or <body> at the end
  • Distinguish between Feature Detection and userAgent detection
  • Review using browser developer tools to examine the Document Object Model

You will also use:

  • document.getElementsByClassName()
  • document element nodes
  • document.createDocumentFragment
  • JavaScript Event Handlers and Anonymous Functions

And we will explore interaction with new elements (the media elements).

Journal

To prepare for this session we will Set up Development Platform

  • Create a student template upon which you can build your explorations and assignments

This week please review the objectives and write as many examples as you feel are necessary for you to meet them. If you get stuck you can post a link to a JS BIN in the course blog and ask the other participants for input.

Here are some ideas.

Outcomes for this Session

At the end of this session (and after completion of the session one assignment) you should be able to:

  • Discuss the relationship between HTML5, CSS and JavaScript
    • In one of your pages write a paragraph or two about the relationship between HTML5, CSS and JavaScript
Recommended Reading
Use Strict Mode in all of your JavaScript assignments
  • Understand the various options for where you place your JavaScript within a page: <head>, inline in the <body> or <body> at the end
    • Write one of your assignment pages in JS Bin and then download it, open it, and examine where the JavaScript code is placed in the source code
  • Distinguish between Feature Detection and userAgent detection
    • Write an example that uses Feature Detection to check if an HTML5 JavaScript API is available
    • Notes: Feature Detection
      continue class work (draggable, media capture) post a link to your attempts to do this in the course blog so that we can all look at this together.
Use document.getElementsByClassName("")
  1. Create a simple web page with several similar elements and add a class name to several of them
  2. Write a script that changes only the elements with that class name
Event Handler

Create a web page that uses element.addEventListener for two different events

  1. for the first event use an anonymous function for the handler
  2. for the second event use a regular function for the handler (i.e. write function first and then reference it)
Review using browser developer tools to examine the Document Object Model
  • Run one of your pages (not in JS Bin) in two different browsers, and use the browser developer tools (F12) to review the Document Object Model, the Console, and the Debugger

Keep track of the addresses of your pages so that we can review them in the lab. Consider emailing them to yourself at an address where you can access them in the lab.

Update your 00.html page with descriptions for the pages you have written.

  • Login in to PeerWise :IP492W14A
  • Create at least one new question.
  • Answer at least five questions.
    • Correct your answers if necessary.
      • Confirm your answers as you go along.
    • Help where you can to improve explanations.
    • Add comments in the questions.
    • Rate the questions.

Detailed Instructions

Reflect in the course blog


Please click the picture above and answer the following questions in the course blog.

Highlights / Metacognition
  • What did you think was the most valuable thing that happened for you tonight?
  • What did you learn from that?
  • What will you do with that knowledge?
Questions?
  • Now that we've had our session together, what do you want to know?
  • What could we have done better?

Course Blog Tutorial (video)

HTML5 CSS and JavaScript


Essential JavaScript for HTML5


Context: HTML5 and JavaScript

HTMLCSSJavaScript
Markup Presentation Behaviour

Video /Audio
Canvas element
Offline storage
Form elements
Drag and Drop
Geolocation
Local storage
JavaScript APIs

CSS3

"use strict";
document.getElementsByClassName("");
interact with new elements
interact with new attributes
contenteditable
interact with web storage
canvas
Web Workers
regular expressions in forms


Strict mode "use strict";

ECMAScript5's strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode isn't just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. Strict mode makes several changes to normal JavaScript semantics. First, strict mode eliminates some JavaScript silent errors by changing them to throw errors. Second, strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. Third, strict mode prohibits some syntax likely to be defined in future versions of ECMAScript. Strict Mode (Mozilla Developer Network)

Things you can't do in strict mode. You can't:

  • Use undeclared variables (must use var. This means no more (accidental) implicit declarations)
  • Duplicate arguments in functions | function myFunction( name, address, name ) {}
  • Use future keywords (class enum export extends import super implements interface let package private protected public static yield)
  • Duplicate properties | var myCar = { make: "Ford" , model: "Fairlane", make: "500" };
  • Use of "eval" as identifier (see first link below)
  • Assignment to a non-writable property
  • Assignment to a non-extensible object
  • Delete undeletable property
  • Octal
  • "eval" variable introduction

http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ (down to but not including discussion on JSON)

http://caniuse.com/#feat=use-strict

Article: Call JavaScript Functions without using eval.

Simple version:

You can limit strict mode to the contents of a function.

You can wrap all of your JavaScript in a library inside a function to apply strict mode to your code only. This is less intrusive on other code or libraries that may not be using "use strict".

Avoid Error Messages

If you are using jsbin add this to the top of the JavaScript panel.


Sample template for use with JS BIN

Feature Detection (NOT userAgent Detection)

Feature detection (NOT userAgent)

document.getElementsByClassName example

Here is a test for <input type="number">

Assuming that you have this html

see this running live in jsbin

more interesting version - show form only if the feature is supported


Here is an example testing for the Vibration API



Types of Feature Detection
  1. testing for a property of the global object (e.g. geolocation)
  2. testing if a property exists for an element
  3. testing for methods of an element
  4. testing for a property by setting a value and testing if that value is retained (e.g. <input> types supported

Detecting HTML5 Features — Dive Into HTML5

User Timing API: Detecting (Testing for a method)

Detecting User Timing API See It Live: Detecting User Timing API


Comprehensive version including writing results to screen See it live: Comprehensive version including writing results to screen



Do you want to write your own?

You can make up your own tests or use a tool like modernizr

In the head section of your html page (assuming that you have modernizr.js in the same folder)

In the body section of your page.

More: modernizr

Resources

Working with the Document Object Model

In most modern browsers you can access developer tools by pressing the F12 Key.


document.getElementsByClassName

Returns a set of elements which have all the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName on any element; it will return only elements which are descendants of the specified root element with the given class names.

See source code examples below

An html collection is not an array but you can address elements within it with [i] or ["name"]. If you need to convert an html collection to an array use this.

See: http://caniuse.com/getelementsbyclassname

Live Example: document.getElementsByClassName("popup") example open preview window

The first three links will open in a popup window.
Course Descriptions
JavaScript description
jQuery description
UBC (not in a popup)

Working with Nodes

In the Document Object Module the main pieces (nodes) that concern us with JavaScript:

  • Element_node
    • document.getElementById("")
    • document.getElementsByTagName("")
    • document.getElementsByClassName("")
  • Attribute_node
  • Text_node
What will you do with/to an Element

Changing an attribute.


Example - Creating, Appending, and Inserting Elements and TextNodes

JavaScript Event Handlers and Anonymous Functions

Using JavaScript to interact with the new features in HTML5 and our users (of course) requires that we understand events.

Event Handlers Inline, ById

Live version of this discussion Event Handlers and Anonymous Functions


Consider this form and notice the inline event handler onclick = "thankyou();"


To separate the behaviour from the layout you would NOT use the inline event handler. Starting here's the HTML without it.


Here is the approach using JavaScript to create event listeners.

Cross Browser Issue

Internet Explorer 8 and earlier used this form

to write in a browser agnostic manner you could do this:

A Quick Reminder About Arrays

A quick look at Arrays


Review: Arrays

Discuss Form Elements and Arrays

Event Handlers Inline, ById, ByTagName, ByClassName

Live version of this discussion Event Handlers Inline, ById, ByTagName, ByClassName


In this example we will attach event handlers Inline, ById, ByTagName, ByClassName.

The HTML

Here is the approach using JavaScript to create event listeners.

The JavaScript


And we need some CSS help to make this work.

The Stylesheet

CSS Selectors and JavaScript (and jQuery)

We will start of with the three most common selectors that all us to find elements within the Document Object Model.

CSS Selectors demo using JavaScript see it in jsbin

CSS Selectors demo using jQuery see it in jsbin

Related reading

Event Logging with Firebug

Here is how you can see events firing in your web pages. (click to view)


In Firefox...

Image:EventLoggingWithFirebug01.jpg


Image:EventLoggingWithFirebug02.jpg


And similar capabilities in other browsers.

In most modern browsers you can access developer tools by pressing the F12 Key.


Interaction with new elements

Video

It is really simple to add a video element to your page.


AND

You can interact with it with JavaScript.

Methods

Properties

Events

HTML5 Video and JavaScript Methods and Events

(e.g. video, localStorage)








Session Two

After this session you will be able to:

Use JavaScript with CSS

We will be using JavaScript to apply styles to HTML elements by tagName. It gets interesting when you do this in response to events.

Keywords:

Use a JavaScript Polyfill for <details>
Use HTML5 data- attributes and dataset
Learn about
  • JavaScript Common Errors
  • JavaScript try... catch... finally...

Journal

  • Have you ever needed to change the appearance of portions of a web page in response to user actions?
  • Have you used browser cookies?

To prepare for this session we will

Show and Tell Lab
  • How did we do with PeerWise
  • Team up and Show your pages to a partner.
  • Talk about
    • What you did: Issues and challenges you encountered while doing the work.
    • What you learned.
    • How you will apply what you learned.
Outcomes

At the end of this session you should be able to

  • Identify the concepts that you used in the page you are sharing with your partner
  • Discuss the challenges you had to overcome to make it work
  • Describe what you learned
  • Discuss how you will apply what you learned in another context
  • Help your partner by suggesting solutions or improvements where appropriate

Writing JavaScript

Use jsbin or similar online tool to create two three pages that demonstrate the following principles. Then migrate the functional parts to new pages on the FTP site (your_name00.html...)


Use document.querySelectorAll("list")
  1. Create a simple web page with several similar elements but not the same tag or class.
  2. Write a script that changes only the elements that match a list you put in here: document.querySelectorAll(list).

This will be like the lab work except that you are using document.querySelectorAll(list) instead of document.getElementsByClassName(classname).

Notes: JavaScript and CSS Selectors

Interacting with Media
data- attribute and dataset
JavaScript polyfill for <details>
  1. Create a web page that uses the polyfill for <details>
  2. Notes: JavaScript polyfill for <details>
  3. link to working example
document.createDocumentFragment()
Explore on your own

Keep track of the addresses of your JS BIN pages (put links to them in your HTML pages) so that we can review them in the lab.

  • Login in to PeerWise :IP492W14A
  • Create at least one new question.
  • Answer at least five questions.
    • Correct your answers if necessary.
      • Confirm your answers as you go along.
    • Help where you can to improve explanations.
    • Add comments in the questions.
    • Rate the questions.

Detailed Instructions

Reflect in the course blog


Please click the picture above and answer the following questions in the course blog.

Highlights / Metacognition
  • What did you think was the most valuable thing that happened for you tonight?
  • What did you learn from that?
  • What will you do with that knowledge?
Questions?
  • Now that we've had our session together, what do you want to know?
  • What could we have done better?

Course Blog Tutorial (video)

News

Review Exercise

Adding event handlers.

Let's look at this together in jsbin

JavaScript and CSS Selectors

We will be using JavaScript to apply these styles to HTML elements by tagName. It gets interesting when you do this in response to events.

Keywords:

More

Here is the JavaScript

See it live:JavaScript and CSS selectors

Mini-challenge
Write your own version of the function: addListeners(tagName) that works with classes or a list of selectors using document.querySelectorAll("selector list"). That would be addListeners(className) or addListeners("selector list").

JavaScript Polyfill for <details>

Quick discussion. This isn't really a true polyfill


A polyfill, or polyfiller, is a piece of code (or plugin) that provides the technology that you, the developer, expect the browser to provide natively. Flattening the API landscape if you will. — polyfill - Remy Sharp

So this is not a polyfill, but it's close, and it give us an example of using JavaScript and CSS selectors to give us some of the functionality of an HTML5 element: <details> .

See source code

See it live: JavaScript to show/hide details


Modified version of Remy Sharp polyfill puts a rotating icon in front of the summary element
version 2 with documentation

data- attribute and dataset

data- attribute and dataset

example 1

JavaScript Event Handlers and data- attribute and dataset
See it live in JS Bin (view the console to see the results).

example 2

Using the data- attribute e.g. <div id="pet" data-office="Prime Minister of Canada" data-year="1970" data-firstname="Pierre" data-lastname="Trudeau">Pierre Elliot Trudeau</div>

See source code


How would you handle our new Prime Minister?

Read data- attributes and write out to the page

Here is another div that we will use for output

Write new data to the original div and retrieve it using element.dataset.data-name

One more example: Another div into which we will write some data


And writing and reading to the element.dataset


See it live in JS Bin: data- attribute and dataset

See: http://caniuse.com/dataset

Article: Custom data-attributes



Counterpoint: jQuery

Native JavaScript Equivalents of jQuery Methods - Craig Buckler

JavaScript Common Errors

First... many of the common errors will be caught by "use strict"

Syntax Errors

My Function is Not Defined

Calling a function that does not exist.

  • throws an error
  • mistyping (case)
  • document.getElementById (watch the case)
  • this also comes up if you mistype the name of a object method.
  • can occur if your function is inside a self-executing function and your call is out-of-scope for that function.

Equality or Assignment

if ( a = b ) should be if ( a == b ) or if ( a === b )


Function arguments

Too many or too few.

function sum( a, b, c ) {
return a + b + c
}
 
var answer = sum( 2, 3)
 
returns NAN


Updating the DOM in excess

use document.createDocumentFragment

Create fragments to avoid updating the Document Object Model multiple times.

See it live: Adding DOM elements individually or fragments
document.createDocumentFragment article by John Reisig

the example uses self-invoking functions

JavaScript Scoping and Hoisting

In JavaScript, a name enters a scope in one of four basic ways:

  1. Language-defined: All scopes are, by default, given the names this and arguments.
  2. Formal parameters: Functions can have named formal parameters, which are scoped to the body of that function.
  3. Function declarations: These are of the form function foo() {}.
  4. Variable declarations: These take the form var foo;.

Function declarations and variable declarations are always moved (“hoisted”) invisibly to the top of their containing scope by the JavaScript interpreter. Function parameters and language-defined names are, obviously, already there.

More ... JavaScript Scoping and Hoisting

Debugging Tools


JavaScript try ... catch ... finally

The try statement consists of a try block, which contains one or more statements, and at least one catch clause or a finally clause, or both. That is, there are three forms of the try statement: * try...catch * try...finally * try...catch...finally A catch clause contain statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch clause. If no exception is thrown in the try block, the catch clause is skipped. The finally clause executes after the try block and catch clause(s) execute but before the statements following the try statement. It always executes, regardless of whether or not an exception was thrown or caught. You can nest one or more try statements. If an inner try statement does not have a catch clause, the enclosing try statement's catch clause is entered. You also use the try statement to handle JavaScript exceptions.
try ... catch MDN

Example

View the JavaScript

Nested try ... catch ... finally

View the JavaScript
See it live: try ... catch ... finally Check the console.

References:

Outcomes

At the end of this section you should be able to:

  • Identify situations where it is appropriate to use try ... catch (see: localstorage-pattern)
  • Discuss
    • When each part (try catch finally) happens
    • When the finally block is executed
  • Write a function with a try ... catch ... finally block within a short program that demonstrates catching an error and handling it.



Web Storage

Web Apps can start faster and work even if there is no internet connection, thanks to the HTML5 App Cache, as well as the Local Storage, Indexed DB, and the File API specifications.

This is basically a client-side database where values are stored in name=value pairs, as strings. This data is not transmitted across the web unless you specifically write your programs to force this to happen. Normally the data resides on the user's local machine.


Limitations: 5 megabytes (per origin) If you exceed 5 megabytes an error is thrown "QUOTA_EXCEEDED_ERR"

Demo Site examples


Note: If you retrieve data from storage, remember that it comes back as a string and you may need to convert that string to use it in your programs.

Example One: Numbers

// setting a sessionStorage item called "pageCounter" to 0
sessionStorage.setItem('pageCounter',0)
 
// creating a variable and retrieving the pageCounter value
// note that we have to convert the sessionStorage item to a number 
var pageCount = parseInt(sessionStorage.pageCounter);

Example Two: Boolean

// setting a sessionStorage item called "isMember" to true
sessionStorage.setItem('isMember',true)
 
// creating a variable and retrieving the pageCounter value
// the expression "parseInt(sessionStorage.isMember=="true")" 
//    returns boolean true or false 
var isMember = parseInt(sessionStorage.isMember=="true");


sessionStorage

Short attention span - basically until the user closes the browser window.


Session Storage live example jsbin

localStorage

Persistent and so much better than cookies. The data persists until you remove it.

localStorage live example jsbin

Security

Local Storage (a.k.a. Offline Storage, Web Storage)
  • Underlying storage mechanism may vary from one user agent to the next. In other words, any authentication your application requires can be bypassed by a user with local privileges to the machine on which the data is stored. Therefore, it's recommended not to store any sensitive information in local storage.
  • Use the object sessionStorage instead of localStorage if persistent storage is not needed. sessionStorage object is available only to that window/tab until the window is closed.
  • A single Cross-site_Scripting_(XSS)|Cross Site Scripting can be used to steal all the data in these objects, so again it's recommended not to store sensitive information in local storage.
  • A single Cross-site_Scripting_(XSS)|Cross Site Scripting can be used to load malicious data into these objects too, so don't consider objects in these to be trusted.
  • Pay extra attention to “localStorage.getItem” and “setItem” calls implemented in HTML5 page. It helps in detecting when developers build solutions that put sensitive information in local storage, which is a bad practice.

Source: Open Web Application Security Project

References

Outcomes

At the end of this section you should be able to:

  • Decide when to use sessionStorage or localStorage
  • Write a page that writes, reads, and clears data from localStorage



Contenteditable

View as separate page


<element contenteditable="true" ... >

This is an example of some editable content. Note: It is not saved anywhere so enjoy the moment. Your edits will only persist until you reload the page.
The section below is also editable but we'll use localStorage to save your make your text persist across page loads
Make some changes and reload the page.


See source code

Examples





Assignment 2

Writing JavaScript

Use jsbin or similar online tool to create two three pages that demonstrate the following principles. Then migrate the functional parts to new pages on the FTP site (your_name00.html...)


Use document.querySelectorAll("list")
  1. Create a simple web page with several similar elements but not the same tag or class.
  2. Write a script that changes only the elements that match a list you put in here: document.querySelectorAll(list).

This will be like the lab work except that you are using document.querySelectorAll(list) instead of document.getElementsByClassName(classname).

Notes: JavaScript and CSS Selectors

Interacting with Media
data- attribute and dataset
JavaScript polyfill for <details>
  1. Create a web page that uses the polyfill for <details>
  2. Notes: JavaScript polyfill for <details>
  3. link to working example
document.createDocumentFragment()
Explore on your own

Keep track of the addresses of your JS BIN pages (put links to them in your HTML pages) so that we can review them in the lab.

Session Three

After this session you will be able to:

Use JavaScript to store data in Web Storage
Use JavaScript to capture input from elements set to contenteditable
Use JavaScript Regular Expressions

We will be using JavaScript Regular Expression to search text. This is a lead up to using Regular Expressions for HTML5 form validation in session Four.

Discuss JavaScript Object Literal Syntax to contrast it with JSON below.
Use JSON (JavaScript Object Notation) to store and consume data using JSON JSON.parse() and JSON.stringify().
Use AJAX (Asynchronous JavaScript + XML)
Explore Web Workers

Keywords:

Journal

  • Have you ever needed to manipulate the content of blocks of text (search, replace, delete)?
  • Have you ever needed to change the content of portions of a web page in response to user actions?

To prepare for this session we will

Show and Tell Lab
  • How did we do with PeerWise
  • Team up and Show your pages to a partner.
  • Talk about
    • What you did: Issues and challenges you encountered while doing the work.
    • What you learned.
    • How you will apply what you learned.
Outcomes

At the end of this session you should be able to

  • Identify the concepts that you used in the page you are sharing with your partner
  • Discuss the challenges you had to overcome to make it work
  • Describe what you learned
  • Discuss how you will apply what you learned in another context
  • Help your partner by suggesting solutions or improvements where appropriate

Writing JavaScript

Use jsbin or similar online tool to create two three pages that demonstrate the following principles. Keep track of the addresses of your pages so that we can review them in the lab.

We may have started work on these during the lab, so you can use the lab work as a starting point and complete anything that you haven't got working yet.

Regular Expressions
  • Write or find a Regular Expression for a pattern that you will need to test in a web page. If you don't have an application for a Regular Expression try something like:
    • postal code (Canadian or US) test for both in the same Regular Expression
    • telephone number (international or local telephone number) test for both, and must include area code
    • firstname (must be longer than a single letter), lastname (must be longer than single letter)
    • exclude specific string of characters. For example - you want to filter out references to http://ebay.com or http://ebay.ca or ebay in any other form but you don't want to filter out "there's a boat down by the bay"


try ... catch ... finally
  • Read this short article about try... catch and localStorage
  • Write a function with a try ... catch ... finally block within a short program that demonstrates catching an error and handling it. It doesn't have to use localStorage, but it can if you like.


AJAX / JSON
  • Create a working example of a page that uses AJAX to pull text from another page (AJAX source) in response to a user event.
  • Create a working example of a page that uses AJAX to pull a JSON object from another page in response to a user event.

There are some sample files on the Microsoft Azure site that you can try: z_AjaxSample01.txt, z_AjaxSample02.txt, z_AjaxSample03.txt

Web Storage
  • Create a working example that uses localStorage to save data provided by a user, and then later allows you to retrieve that data. This could be an opporutunity to explore using contenteditable.

  • Login in to PeerWise :IP492F15A
  • Create at least one new question.
  • Answer at least five questions.
    • Correct your answers if necessary.
      • Confirm your answers as you go along.
    • Help where you can to improve explanations.
    • Add comments in the questions.
    • Rate the questions.

Detailed Instructions

Reflect in the course blog


Please click the picture above and answer the following questions in the course blog.

Highlights / Metacognition
  • What did you think was the most valuable thing that happened for you tonight?
  • What did you learn from that?
  • What will you do with that knowledge?
Questions?
  • Now that we've had our session together, what do you want to know?
  • What could we have done better?

Course Blog Tutorial (video)


Web Storage

Web Apps can start faster and work even if there is no internet connection, thanks to the HTML5 App Cache, as well as the Local Storage, Indexed DB, and the File API specifications.

This is basically a client-side database where values are stored in name=value pairs, as strings. This data is not transmitted across the web unless you specifically write your programs to force this to happen. Normally the data resides on the user's local machine.


Limitations: 5 megabytes (per origin) If you exceed 5 megabytes an error is thrown "QUOTA_EXCEEDED_ERR"

Demo Site examples


Note: If you retrieve data from storage, remember that it comes back as a string and you may need to convert that string to use it in your programs.

Example One: Numbers

// setting a sessionStorage item called "pageCounter" to 0
sessionStorage.setItem('pageCounter',0)
 
// creating a variable and retrieving the pageCounter value
// note that we have to convert the sessionStorage item to a number 
var pageCount = parseInt(sessionStorage.pageCounter);

Example Two: Boolean

// setting a sessionStorage item called "isMember" to true
sessionStorage.setItem('isMember',true)
 
// creating a variable and retrieving the pageCounter value
// the expression "parseInt(sessionStorage.isMember=="true")" 
//    returns boolean true or false 
var isMember = parseInt(sessionStorage.isMember=="true");


sessionStorage

Short attention span - basically until the user closes the browser window.


Session Storage live example jsbin

localStorage

Persistent and so much better than cookies. The data persists until you remove it.

localStorage live example jsbin

Security

Local Storage (a.k.a. Offline Storage, Web Storage)
  • Underlying storage mechanism may vary from one user agent to the next. In other words, any authentication your application requires can be bypassed by a user with local privileges to the machine on which the data is stored. Therefore, it's recommended not to store any sensitive information in local storage.
  • Use the object sessionStorage instead of localStorage if persistent storage is not needed. sessionStorage object is available only to that window/tab until the window is closed.
  • A single Cross-site_Scripting_(XSS)|Cross Site Scripting can be used to steal all the data in these objects, so again it's recommended not to store sensitive information in local storage.
  • A single Cross-site_Scripting_(XSS)|Cross Site Scripting can be used to load malicious data into these objects too, so don't consider objects in these to be trusted.
  • Pay extra attention to “localStorage.getItem” and “setItem” calls implemented in HTML5 page. It helps in detecting when developers build solutions that put sensitive information in local storage, which is a bad practice.

Source: Open Web Application Security Project

References

Outcomes

At the end of this section you should be able to:

  • Decide when to use sessionStorage or localStorage
  • Write a page that writes, reads, and clears data from localStorage



Contenteditable

View as separate page


<element contenteditable="true" ... >

This is an example of some editable content. Note: It is not saved anywhere so enjoy the moment. Your edits will only persist until you reload the page.
The section below is also editable but we'll use localStorage to save your make your text persist across page loads
Make some changes and reload the page.


See source code

Examples



Regular Expressions

Regular expressions are patterns that we can use for validating text. Here is a regular expression for alphanumeric input.

var re = new RegExp ("^[a-zA-Z0-9]+$");

that could also be written

var re = /^[a-zA-Z0-9]+$/;

Note the anchors

  • ^ matches the beginning of the string
  • $ matches the end of the string

Character classes

  • [aeiou] matches any of the vowels
  • [^aeiou] matches if NOT there are no vowels

Repeating character classes

  • +
  •  ?
  • *


Regular Expressions Introduction

Live example: Regular Expressions introduction

Regular Expressions to Search Text

Live example: Search using Regular Expressions


Outcomes

At the end of this section you should be able to:

  • Describe what Regular Expressions are and how they are used
  • Write or find a Regular Expression for a pattern that you will need to test in a web page. If you don't have an application for a Regular Expression try something like:
    • postal code (Canadian or US) test for both in the same Regular Expression
    • telephone number (international or local telephone number) test for both, and must include area code
    • firstname (must be longer than a single letter), lastname (must be longer than single letter)
    • exclude specific string of characters. For example - you want to filter out references to http://ebay.com or http://ebay.ca or ebay in any other form but you don't want to filter out "there's a boat down by the bay"


JavaScript Object Literal Syntax

This discussion is in preparation for the section on JSON below.


This is a quick review of JavaScript Object Literal Syntax.

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.
Object_literals MDN

View the JavaScript
See it live: JavaScript Object Literal Syntax Check the console.

Another version that uses an anonymous function for age.

View the JavaScript
See it live: JavaScript Object Literal Syntax Check the console.


Outcomes

At the end of this section you should be able to:

  • Identify a JavaScript Object literal
  • Write a JavaScript Object literal that includes a short anonymous function



JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
Introducing JSON (json.org)

  • Format for sharing data
  • Derived from JavaScript but
    • language independent (C, Ruby, Perl, Php)
    • human readable

e.g. creating a variable with JSON data. Note the double quotation marks around both the keys and the data.

JSON is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON, and some JSON is not JavaScript. JavaScript Object Notation MDN

Methods

parse
Parse a string as JSON, optionally transform the produced value and its properties, and return the value.
stringify
Return a JSON string corresponding to the specified value, optionally including only certain properties or replacing property values in a user-defined manner.

See the source code

And using that data and displaying it in a web page

View the HTML

See the source code

See it live - JSON example - jsbin http://jsonlint.com/ JSON validator


Outcomes

At the end of this section you should be able to:

  • Identify situations when you might use JSON
  • Distinguish between a JSON data structure and a JavaScript object
  • Write some JSON data and display it (all in the same jsbin file)
  • Determine when to use JSON.stringify() and JSON.parse()



AJAX

Asynchronous JavaScript + XML, while not a technology in itself, is a term coined in 2005 by Jesse James Garrett, that describes a "new" approach to using a number of existing technologies together, including: HTML or XHTML, Cascading Style Sheets, JavaScript, The Document Object Model, XML, XSLT, and the most importantly XMLHttpRequest object. When these technologies are combined in the AJAX model, web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions. Although X in AJAX stands for XML, JSON is used more than XML nowadays because of its many advantages such as being lighter and a part of JavaScript. Both JSON and XML are used for packaging information in AJAX model.
AJAX (MDN)

AJAX to Get Raw Text - Very Simple



Here is a page where we want to see the data.

See the HTML where we will display the data

And requesting that data and displaying it in a web page

View the JavaScript

See it live in JS Bin - AJAX - raw text - very simple

AJAX to get raw text

Here is a page where we want to see the data.

See the HTML where we will display the data



And requesting that data and displaying it in a web page

View the JavaScript

See it live - AJAX - raw text

AJAX Examining the Process

We'll keep it simple and grab a text file that has some HTML in it, and display it.

See the text object on the web
live text file on the web. It's posted on jsbin so that it will be on the same domain as the live example that will consume it.

And here is a page where we want to see the data.

See the HTML where we will display the data
And requesting that data, reporting through the steps and displaying it in a web page
View the JavaScript
See it live JS Bin - AJAX tracking the process, simple text file

AJAX to get JSON object

See the JSON object on the web
live JSON object on the web You may need to copy/paste the url into Google Chrome to see the data

And here is a page where we want to see the data.

See the HTML where we will display the data


And requesting that data and displaying it in a web page

View the JavaScript

See it live - AJAX with JSON

Outcomes

At the end of this section you should be able to:

  • Identify reasons when you would want to use AJAX
  • Create a working example of a page that uses AJAX to pull text from another page (AJAX source) in response to a user event.
  • Create a working example of a page that uses AJAX to pull a JSON object from another page in response to a user event.



Web Workers

HTML5 Web Worker - be sure to terminate worker when you are finished with it (click the button on the screen).


Web Workers

Web Worker Demo



Assignment

To be completed before {{{Assignment 3}}}



Session Four

After this session you will be able to:

Use JavaScript Regular Expressions with HTML5 Forms

We will be using JavaScript Regular Expressions with the pattern attribute

SVG — create a simple SVG element that responds to a user event
  • click event
  • call a JavaScript function to change the size or trigger an animation
Canvas — create a canvas with basic shapes and respond to user event
Drag and Drop — examine the event model
Application Cache
Device Access
  • Geolocation

Keywords:

Journal

  • How much time have you devoted to field level validation in forms on the client-side?
  • Does client-side validation mean that you no longer need server-side validation?
  • Have you used SVG images in your web pages?
  • Have you used the Canvas element?

To prepare for this session we will

Show and Tell Lab
  • How did we do with PeerWise
  • Team up and Show your pages to a partner.
  • Talk about
    • What you did: Issues and challenges you encountered while doing the work.
    • What you learned.
    • How you will apply what you learned.
Outcomes

At the end of this session you should be able to

  • Identify the concepts that you used in the page you are sharing with your partner
  • Discuss the challenges you had to overcome to make it work
  • Describe what you learned
  • Discuss how you will apply what you learned in another context
  • Help your partner by suggesting solutions or improvements where appropriate

Please remember to do an entry in the course blog and add at least one more question and answer all unanswered questions in PeerWise.
Writing JavaScript

Try your hand at least three of the following. Pick the ones that seems to have the most immediate application for you that you have not done in previous assignments. Remember: The less you copy and paste, the more you will understand.

Send me an email JimUBC@live.com with links to your work in jsbin or jsfiddle or any environment where I will be able to see all the source code for your work.

  • Login in to PeerWise :IP492F15A
  • Create at least one new question.
  • Answer at least five questions.
    • Correct your answers if necessary.
      • Confirm your answers as you go along.
    • Help where you can to improve explanations.
    • Add comments in the questions.
    • Rate the questions.

Detailed Instructions

Reflect in the course blog


Please click the picture above and answer the following questions in the course blog.

Highlights / Metacognition
  • What did you think was the most valuable thing that happened for you tonight?
  • What did you learn from that?
  • What will you do with that knowledge?
Questions?
  • Now that we've had our session together, what do you want to know?
  • What could we have done better?

Course Blog Tutorial (video)


CSS3

HTML5 Powered with CSS3 / Styling Optional Review: HTML5 CSS3

Regular Expressions

Optional review: JavaScript Regular Expressions


HTML5 Forms

Form Examples on demo site

A Form That Grows

In the form below, each Company [label and input field] is in a paragraph with a separate id. (p1, p2, ...)
This allows us to add or remove paragraphs that contain input labels and fields


Style

HTML

JavaScript

The whole page

See the live working example on jsbin

See the live working example on codepen.io

New Input Types

These are the new input types in HTML5.
Note: If you use one of the new input types if it’s not supported in the web browser, it will default back to a regular <input type=”text”> element. There are no errors, and no multiple code versions to write.
Input TypeDescription
color Gives the end user a native color picker to choose a color.
date Offers a datepicker.
datetime-local An element to choose both date and time, with local settings support.
email A field for entering e-mail address(es) with validation
month Choose a full month. (year / month)
number Picking a number. (uses a spinner)
range Enter a value/position using a slider.
search  A field for search queries.
tel Enter a telephone number.
time Input a time
url Enter a URL
week Picking a specific week ( year / week)

New Attributes

Form Attributes

Please see Form with a Fieldset and HTML5 Form Elements example

Form with a Fieldset and HTML5 Form Elements

Right click link below and open in a new window.

HTML5 Form Elements

New attributes for <form>:

  • autocomplete (entire form)
The autocomplete attribute specifies whether a form or input field should have autocomplete on or off. When autocomplete is on, the browser automatically complete values based on values that the user has entered before. Source
  • novalidate
The novalidate attribute is a boolean attribute. When present, it specifies that the form-data (input) should not be validated when submitted. Source
Input Attributes
  • autocomplete (individual input)
  • autofocus
  • form
  • formaction
  • formenctype
  • formmethod
  • formnovalidate
  • formtarget
  • height and width
  • list
  • min and max
  • multiple
  • pattern (regexp)
  • placeholder
  • required
  • step
More Form Tips

Validation

Perhaps the easiest validation to add is "required"

<input type="text" id="LastName" name="LastName" required>
 
or 
 
<input type="text" id="LastName" name="LastName" required="required">

Tied in with the new input types is field level validation for email, url, number, tel, date, etc.

HTML5 Form Validation with Regular Expressions

Quick introductory example: Form validation using regular expressions

Comparing validation with JavaScript vs. pattern= attribute


Form field validation in HTML5 is much simpler than it used to be. It used to require lots of JavaScript to verify that the data input in the typical text field was suitable. Now, with several new input types, that is simpler.

There is also a new pattern = "" attribute that allows us to specify a regular expression that must be matched.

Source code
All the work is done in HTML but notice the regular expressions in lines 22, 32.
We are also using the multiple attribute in line 41 (but not in 43). See it live: HTML5 Form Validation with Regular Expressions (and multiple)


article: HTML5 Form Validation with Regex


HTML5 Form Validation with Novalidate option

Form with NoValidate and LocalStorage

HTML5 Form Novalidate and LocalStorage

Note the option to save data (without validation)










Style

HTML

JavaScript

See the live working example on jsbin


Resources

Graphics and Effects

Graphics & Effects:

Between SVG, Canvas, WebGL, and CSS3 3D features, you're sure to amaze your users with stunning visuals natively rendered in the browser.

SVG

SVG is a widely-deployed royalty-free graphics format developed and maintained by the W3C SVG Working Group. Scalable Vector Graphics W3C

Can I use SVG

Scalable Vector Graphics (click image above to see JavaScript in action).

SVG Basics

The coordinate system

The default coordinate system in SVG is much the same as in HTML. It works as a two-dimensional x-y plane. The origin (where x=0 and y=0) is the upper left-hand corner. As we move right from there, x increases. As we move downward, y increases. Generally, units are measured in pixels. That is, if our browser window has a rectangle of 343 pixels high by 501 pixels wide then the lower right corner of that window will be the point (501,343).

Image:SVGCoordinates.png

Raster to SVG conversion:

http://image.online-convert.com/convert-to-svg

http://vectormagic.com


— Source: SVG Basics

(please follow the link above for a nice tutorial about SVG Graphics from w3.org

— Source: w3c.org SVG

SVG Example

Add this to the body of one of your pages.


<svg  xmlns="http://www.w3.org/2000/svg"
      xmlns:xlink="http://www.w3.org/1999/xlink"
      width="300" height="300">
<g  id="svgCircles" transform="scale(1)" onclick="scaleup(10,1,'svgCircles');">
    <circle r="50" cx="50" cy="50" fill="red"/>
    <circle r="40" cx="50" cy="50" fill="green"/>
    <circle r="30" cx="50" cy="50" fill="blue"/>
    <circle r="20" cx="50" cy="50" fill="yellow"/>
</g>
 
<script><![CDATA[
    var scaled = false;   // toggle to determine if already scaled
    function scaleup(scalefactor, scalenormal, elem) {
        if (scaled) { scalefactor = scalenormal; }
        var x = document.getElementById(elem);
        x.setAttribute("transform", "scale(" + scalefactor + ")");
        scaled = !scaled;
    }
]]></script>
</svg>
The SVG Logo

Scalable Vector Graphics

<svg width="540" height="200" viewBox="0 0 540 200" style="margin:-2em 0em -3em 0em">
               <defs>
                 <radialGradient id="radial" cx="50%" cy="50%" fx="25%" fy="25%">
                   <stop offset="0%" stop-color="#60bafc"></stop>
                   <stop offset="50%" stop-color="#409adc"></stop>
                   <stop offset="100%" stop-color="#005a9c"></stop>
                 </radialGradient>
 
                 <path id="curve" d="M18,60 C100,10 180,110 264,60" fill="none"></path>
               </defs>
<g id="svglogo" transform="scale(1.0)" onclick="scaleup(3.0,1.0,'svglogo');">
               <circle cx="138" cy="50" r="38" fill="url(#radial)" stroke="#005a9c"></circle>
 
               <text font-family="Verdana" font-size="20" fill="#ff9900"><textPath xlink:href="#curve" method="stretch" style="visibility: visible;">Scalable <tspan fill="white">Vector</tspan> Graphics</textPath></text>
</g>    
<script><![CDATA[
    var scaled = false;   // toggle to determine if already scaled
    function scaleup(scalefactor, scalenormal, elem) {
        if (scaled) { scalefactor = scalenormal; }
        var x = document.getElementById(elem);
        x.setAttribute("transform", "scale(" + scalefactor + ")");
        scaled = !scaled;
    }
]]></script>        
</svg>

The text is on a Cubic Bezier Curve;

Drawing cubic Bezier curves is done using the C and c commands. Cubic Bezier curves are like quadratic Bezier curves except they have two control points instead of one. Like with lines, the uppercase command (C) uses absolute coordinates for its endpoint, where the lowercase command (c) uses relative coordinates (relative to the start point).

source

SVG Animation

This doesn't work in all browsers yet. Try a few different browsers in the lab.

<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">
 
    <rect x="10" y="10" height="110" width="110"
         style="stroke:#ff0000; fill: #0000ff">
 
        <animateTransform
            attributeName="transform"
            begin="0s"
            dur="20s"
            type="rotate"
            from="0 60 60"  
            to="360 60 60"
            repeatCount="indefinite" 
        />
    </rect>
 
</svg>

Pseudo code (not functional because of the /* comments */ )


<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">
 
    <rect x="10" y="10" height="110" width="110"
         style="stroke:#ff0000; fill: #0000ff">
 
        <animateTransform
            attributeName="transform"
            begin="0s"
            dur="20s"
            type="rotate"
            /* rotate from 0-360&deg; around the middle of the rectangle (60,60) */
            from="0 60 60" /* beginning degrees, x-centre point for rotation, y-centre point for rotation */ 
            to="360 60 60" /* beginning degrees, x-centre point for rotation, y-centre point for rotation */
            repeatCount="indefinite" 
        />
    </rect>
 
</svg>

— Source: jenkov.com svg animation tutorial

SVG Animation with JavaScript

Click to start the animation.


See it live: SVG Animation with JavaScript

Elliptical Arcs

Image:FourEllipticalArcs.png

Four elliptical arcs sharing endpoints

This example may be seen at http://srufaculty.sru.edu/david.dailey/svg/newstuff/arcs.svg

<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M100 100 A 30,50 0 0,0 200,150 z"
fill="#080" stroke="#8f8" stroke-width="5" opacity="0.5"/>
 
 <path d="M100 100 A 30,50 0 0,1 200,150 z"
fill="#088" stroke="cyan" stroke-width="5" opacity="0.5"/>
 
 <path d="M100 100 A300,30 0 0,0 200,150 "
fill="#880" stroke="yellow" stroke-width="5" opacity="0.5" />
 
 <path d="M100 100 A300,30 0 0,1 200,150 "
id="red" fill="#800" stroke-width="5" opacity="0.5"/>
 
</svg>


— Source: Elliptical Arcs

SVG - Traversing the DOM

Please see: http://vector-graphics.appspot.com/t002.html

SVG References

What Everybody Ought to Know About SVG Right Now

W3C SVG Primer

SVG Authoring Guidelines

Scriptdraw SVG Script Editor - demo tool

SVG in HTML5 - examples

SVG Edit:SVG-edit is a fast, web-based, JavaScript-driven SVG drawing editor that works in any modern browser.

Outcomes

At the end of this section you should be able to

  • Recognize SVG images (Document Object Model Objects) in HTML source code
  • (optional) Write JavaScript to interact with the SVG image object by manipulating the SVG DOM object
  • After doing the section on HTML Canvas, you should be able to distinguish between the two technologies.

Canvas

Graphics & Effects:

Canvas is another tool for bringing graphics to your web pages with HTML5. SVG, Canvas, WebGL, and CSS3 3D features, allow you to present stunning visuals natively rendered in the browser.

Introduction and key ideas.

Please see Canvas - Full Discussion and Demos


Source:



Canvas Basics to Try

HTML for three canvas objects.

See more

Script that draws on the Canvas objects.

See the JavaScript


Your browser does not support canvas. Your browser does not support canvas but 
    this is a picture of what you would see if it did.
Your browser does not support canvas. Your browser does not support canvas but 
    this is a picture of what you would see if it did.
Your browser does not support canvas. Your browser does not support canvas but 
    this is a picture of what you would see if it did.

See it live: Canvas basics to try

Canvas on the Web

Canvas Example


HTML5 Canvas Boxes Example

Canvas Rectangles in jsbin


Canvas Basic Shapes tutorial in jsbin

Sorry - your browser does not appear to support Canvas
Sorry - your browser does not appear to support Canvas
Sorry - your browser does not appear to support Canvas

Drawing Bubbles example in jsbin


Canvas Drawing Shapes tutorial in jsbin


Your browser does not support canvas. Your browser does not support canvas but 
   this is a picture of what you would see if it did.


In the head section

<script>
    window.onload = function () {
        // Get a reference to the element.
        var elem = document.getElementById("myCanvas");
        //Check for properties and methods, to make sure your code doesn't break 
        // in other browsers.
        if (elem && elem.getContext) {
            // Get the 2d context.
            var context = elem.getContext("2d");
            if (context) {
                // put things you want to execute onload here
                drawBoxes(context);
 
            }
        }
    };
 
    function drawBoxes(context) {
 
        // Draw black rect
        context.fillStyle = "black";
        context.fillRect(50, 20, 145, 145);
 
        // Draw blue rect
        context.fillStyle = "rgb(0, 162, 232)";
        context.fillRect(135, 85, 125, 125);
 
        // Set line width
        context.lineWidth = 5;
 
        // Draw black rect outline
        context.strokeStyle = "rgb(0, 0, 0)";
        context.strokeRect(50, 335, 145, 145);
 
        // Draw blue rect outline
        context.strokeStyle = "rgb(0, 162, 232)";
        context.strokeRect(135, 275, 125, 125);
 
        // Draw semi-transparent yellow rect
        context.fillStyle = "rgba(255, 255, 0, 0.75)";
        context.fillRect(210, 180, 125, 125);
    }
 
</script>

In the body section
.
.
.

<canvas id="myCanvas" width="400" height="500" 
style="margin-top:20px;margin-left:20px">
<!-- fallback text and image for older browsers -->
Your browser does not support canvas.
<img alt="Your browser does not support canvas but 
   this is a picture of what you would see if it did." 
   src="http://dotnet.tech.ubc.ca/CourseWiki/images/0/0d/PictureOfMyCanvas.png">
</canvas>
Canvas Resources

Canvas Scratchpad


Outcomes

At the end of this section you should be able to:

  • Use HTML and JavaScript to add a Canvas object to a web page
  • Use JavaScript to draw fundamental shapes on the Canvas object (line rectangle, arc)
  • Discuss the differences between SVG and Canvas

Comparing SVG and Canvas

How to Choose Between SVG and Canvas

Drag and Drop

HTML5 Drag and Drop API

Drag and Drop is natively supported in HTML5.

Event Based

Seven New Events

  • for draggable items
    • dragstart : when the user begins dragging a draggable element (or selection).
    • drag : when the draggable element is moved during a drag (e.g., with the mouse).
    • dragend : when the user ends the drag and drop operation.
  • for elements that can receive a drop
    • dragenter : when a draggable object is first dragged over an element.
    • dragleave : when a draggable object is dragged outside of an element.
    • dragover : when a draggable object is moved inside an element.
    • drop : when a draggable object is dropped.

Attributes required

  • draggable
  • dropzone (optional)

Register event handlers:

  • element.addEventListener('dragstart", handleDragStart, false);

Events may be fired repeatedly

Inconsistent implementations

Drag Data Store

What makes HTML5 Drag and Drop more interesting than a run-of-the-mill JavaScript drag and drop library is the concept of the drag data store. At the core of every drag and drop operation lies a bucket of information that can be passed around. The data store consists of a data store item list, listing each piece of dragged data. These drag items all have a kind (either “Text” or “File”), a type (a string, usually given as a MIME type), the actual data (a unicode or binary string), and some other information that can be used by the browser to give UI feedback.
The dataTransfer object of a drag event is how we get access to read from, write to, and clear the data in this data store. Each dataTransfer object is also linked to a dataTransferItemList object (accesible via the items getter), which contains one or more dataTransferItem objects (accessible via the index of the dataTransferItemList object).
Drag and Drop : dev.opera.com

See it live


Resources

Drag and Drop onto Canvas

Just for fun (optional discussion).


Drag-and-Drop Example with Canvas

Fixed-size canvas
Drop a file here...

Real-size canvas
Drop a file here...

This is an interesting example because the drag targets are Canvas Elements.

See the HTML where we will display the data
CSS - non critical, just making things easier to see.
The JavaScript where we make it all happen
See it live - Drag and Drop onto Canvas Elements



Application Caching

caniuse Application Caching aka Offline Applications

See it live: clock.html

Quoting W3C

The mechanism for ensuring Web applications are available even when the user is not connected to their network is the manifest attribute on the html element.The attribute takes a URI to a manifest, which specifies which files are to be cached. The manifest has a text/cache-manifest MIME type. A typical file looks like this:
CACHE MANIFEST
index.html
help.html
style/default.css
images/logo.png
images/backgound.png


 
NETWORK:
server.cgi

This file specifies several files to cache, and then specifies that server.cgi should never be cached, so that any attempt to access that file will bypass the cache.The manifest can then be linked to by declaring it in the (HTML) application, like this:

<!DOCTYPE HTML>
<html manifest="cache-manifest">
...

The server.cgi file would be white-listed (put in the NETWORK: section) so that it can be contacted to get updates from the server, as in:

<event-source src="server.cgi">


(The event-source element is a new feature in HTML 5 that allows servers to continuously stream updates to a Web page.)The application cache mechanism also supports a way to opportunistically cache (from the server) a group of files matching a common prefix, with the ability to have a fallback page for rendering those pages when offline. It also provides a way for scripts to add and remove entries from the cache dynamically, and a way for applications to atomically update their cache to new files, optionally presenting custom UI during the update.

Source — http://www.w3.org/TR/offline-webapps/#offline


Application Caching demo

Application Cache demo clock.html

The time is:

HTML

CSS
JavaScript
clock.appcache

Application Cache demo Analog Clock with Canvas

Analog Clock with Canvas using Application Cache

Credit: Saturn Boy

References



Device Access

Device Access:

Beginning with the Geolocation API, Web Applications can present rich, device-aware features and experiences. Incredible device access innovations are being developed and implemented, from audio/video input access to microphones and cameras, to local data such as contacts & events, and even tilt orientation.

Geolocation

The Geolocation API defines a high-level interface to location information associated only with the device hosting the implementation, such as latitude and longitude. The API itself is agnostic of the underlying location information sources. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input. No guarantee is given that the API returns the device's actual location.

The API is designed to enable both "one-shot" position requests and repeated position updates, as well as the ability to explicitly query the cached positions. Location information is represented by latitude and longitude coordinates.

Source: W3C Geolocation API Specification Introduction

Geolocation demo: jsbin

Geolocation with Google Maps JavaScript API v3

Geolocation with Bing Maps API — — Bing Maps API

Geolocation with Bing Maps

Geolocation demo: demo site


More reading

Location Aware Browsing FAQs — Mozilla.org

Device Orientation

Device Orientation Demo

DeviceOrientationEvent is not supported.



Source — mobiforge.com


caniuse Device Orientation

Device Orientation Demo

Device Orientation Demo 2 HTML5 logo.

More about Device Access

HTML5 Device Access video — Intel

Expert Mind Revisited

Follow Expert and Novice

Expert and Novice At the end of this session you should be able to:
  1. Describe how an expert in a particular field approaches a problem.
  2. Describe how a novice in a particular field would approach the same problem.
  3. Identify key differences in the way that an expert and a novice think about problems.
  4. Set a goal for what you would like to be able to do with respect to [whatever brought you here].
  5. Write down how you will know when you have reached the goal.


HTML5 Resource Sites

We need to talk about feature support in browsers. Start here:


Assignment

Assignment 4



Assignments

Assignment 1

To be completed before Monday November 30, 2015 This week please review the objectives and write as many examples as you feel are necessary for you to meet them. If you get stuck you can post a link to a JS BIN in the course blog and ask the other participants for input.

Here are some ideas.

Outcomes for this Session

At the end of this session (and after completion of the session one assignment) you should be able to:

  • Discuss the relationship between HTML5, CSS and JavaScript
    • In one of your pages write a paragraph or two about the relationship between HTML5, CSS and JavaScript
Recommended Reading
Use Strict Mode in all of your JavaScript assignments
  • Understand the various options for where you place your JavaScript within a page: <head>, inline in the <body> or <body> at the end
    • Write one of your assignment pages in JS Bin and then download it, open it, and examine where the JavaScript code is placed in the source code
  • Distinguish between Feature Detection and userAgent detection
    • Write an example that uses Feature Detection to check if an HTML5 JavaScript API is available
    • Notes: Feature Detection
      continue class work (draggable, media capture) post a link to your attempts to do this in the course blog so that we can all look at this together.
Use document.getElementsByClassName("")
  1. Create a simple web page with several similar elements and add a class name to several of them
  2. Write a script that changes only the elements with that class name
Event Handler

Create a web page that uses element.addEventListener for two different events

  1. for the first event use an anonymous function for the handler
  2. for the second event use a regular function for the handler (i.e. write function first and then reference it)
Review using browser developer tools to examine the Document Object Model
  • Run one of your pages (not in JS Bin) in two different browsers, and use the browser developer tools (F12) to review the Document Object Model, the Console, and the Debugger

Keep track of the addresses of your pages so that we can review them in the lab. Consider emailing them to yourself at an address where you can access them in the lab.

Update your 00.html page with descriptions for the pages you have written.

Related Downloads

Online Resources

Reading

Dive into HTML5

Building Apps with HTML5: What you need to know

HTML5 Semantic Markup and Page Layout

Using HTML5's New Semantic Tags Today

W3C HTML5 Reference

HTML5 Semantics

HTML5Please Exploring what is supported in different browsers (what works).

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) - 2003 but still relevant

Activating Browser Modes with Doctype

HTML5 the Hype and the Reality Behind

Hone Your Web Client Skills (with HTML5 and JavaScript)

W3.org

HTML5 Design Principles

HTML5 differences from HTML4


Tools

Sample file to validate:

http://dotnet.tech.ubc.ca/onlinework/html5/zStudent_Template.html

  1. HTML5 Validator (whatwg.org) Note - two validators available there.
  2. HTML5 Validator (validator.nu)
  3. HTML5 Validator (w3.org)
  4. HTML5 Outliner






[[Category:IP492F15A]]



Personal tools