Table of Contents Lectures/060 Week 6... · 2014-01-15 · JavaScript & AJAX IV. HTML5 scriptable...
Transcript of Table of Contents Lectures/060 Week 6... · 2014-01-15 · JavaScript & AJAX IV. HTML5 scriptable...
11
Table of Contents
I. HTML5
II. CSS3
III. JavaScript & AJAX
IV. HTML5 scriptable features
V. SVG
VI. D3
A refresher of HTML5 and related technologies – or what you need to know to get started.
2
(C) 2013 Jonathan Levin, Technologeeks.com
HTML5 is one of a class of markup languages. These are languages not used for
programming and logic, but rather for display and data processing. The idea of
markup is to add “tags” to a given document, specifying its parts, structure, and
semantic significance of its components.
The most widely used markup language is the eXtensible Markup Language, or XML,
which is, in fact, a close sibling of HTML. XML is used primarily for semantic tagging,
and uses specific sub “grammars” to describe everything from address books and
business inventories to natural language annotations. HTML, on the other hand, is
involved in Hyper Text – enriching textual documents by embedding multimedia
content in them, and linking them to one another.
(C) 2013 Jonathan Levin, Technologeeks.com
3
HTML5 and related technologies
4
HTML has undergone many revisions over the years. From HTML/1.0, which was the
first draft, through versions 2.0 and 3.0 (which never got anywhere), to HTML/4.0,
which reigned as the de facto standard for over 10 years. Recently, it has been
superseded by HTML/5.0, which is the emerging standard.
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 and related technologies
HTML5 is fast becoming a de facto standard, merging together HTML 4, XHTML/1.1,
and a host of new features, such as audio and video support, and the exciting
graphics of the canvas and scalable vector graphics (SVG).
Most modern browsers support HTML5, but none do so perfectly. Various sites
demonstrate HTML5 capabilities and provide tests. The highest ranking browser in
terms of compatibility is currently Google’s Chrome.
To make sure web pages are parsed as HTML5, add a <!DOCTYPE HTML><!DOCTYPE HTML><!DOCTYPE HTML><!DOCTYPE HTML> as the
first line of each page. Elements are, as in XHTML, all lowercase.
5
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 and related technologies
It is very important to adhere to standards when writing HTML5 code. There are
many browsers out there – both desktop and mobile, and HTML5 documents, unlike
program code, can be interpreted in many ways. Oftentimes, browsers take liberties
with parsing and rendering HTML, leading to sites which look great in one platform,
and utterly terrible in another.
(C) 2013 Jonathan Levin, Technologeeks.com
6
HTML5 and related technologies
(C) 2013 Jonathan Levin, Technologeeks.com
7
HTML5 and related technologies
HTML5 are special cases of XML documents (technically, of SGML), though in practice
the syntax is much more relaxed: Most manually generated HTML can be invalid XML
(for example, unclosed tags), and still be rendered properly by browsers.
At the highest level, an HTML elements has two parts: its header (<head>) and its
body (<body>). The former contains meta data about the document.
(C) 2013 Jonathan Levin, Technologeeks.com
8
HTML5 and related technologies
HTML5, in addition to many multimedia tags, makes it easier to specify document
and article structure. It offers a set of tags which can be used to semantically classify
portions of the document: main body, sidebars, paragraphs and figures. These, in
turn, can be rendered (using inline styles or style sheets), or be used by screen
readers and scrapers (such as Safari’s built in “reader” feature) to present the content
in a more readable manner.
9
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 and related technologies
Tags which are far less common, but still useful – especially to CS-folk such as
yourselves – are the so called “Geek” tags, which come in handy when citing articles,
displaying code samples, or reproducing textual screen captures.
10
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 and related technologies
Tables are an important part of HTML. In fact, before the advent of CSS, tables were
the chief method of laying out elements.
Tables are mostly straightforward to generate, though can lead to a lot of HTML,
especially if coding by hand. Each table has a head, a body, and a footer, though in
practice these can be omitted, and the table can be specified directly as its rows
(<tr>) and cells (<td>). Cells are normally one row and one column in size, though
they may span multiple rows and/or columns if the appropriate attributes (rowspan
and colspan, respectively) are specified.
CSS3 not only deprecates using tables for layout, but also deprecates inline style
attributes of tables (such as vertical alignment, cell width and height, etc).
(C) 2013 Jonathan Levin, Technologeeks.com
11
HTML5 and related technologies
(C) 2013 Jonathan Levin, Technologeeks.com
12
HTML5 and related technologies
(C) 2013 Jonathan Levin, Technologeeks.com
13
HTML5 and related technologies
The most important addition to HTML5 is the <video> element, which finally provides
a way to display web-based video clips, without needing to resort to flash, which is a
plug-in. HTML5-enabled browsers all support a built-in video player. The element can
be styled with the width and height attributes, and optional controls for the user may
be displayed if the controls attribute is specified.
We are not “there” yet, however: Codec support in HTML5 is not standardized. In
fact, at the time of writing there is no single codec which is supported by the top four
browsers (H.264 comes close, but is not supported by Firefox). Fortunately, this can
be worked around by specifying multiple encodings of the same video clip. The
<source> sub-element is used for that, and the video can be specified by its MIME-
type, codec, or both.
14
<video poster="movie.jpg" controls><source src="movie.ogv" type='video/ogg; codecs="theora, vorbis"'/><source src="movie.mp4" type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'/><p>Your browser supports none of the codecs for this movie, or is not HTML5</p>
</video>
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 and related technologies
The <audio> element follows the same principles as the <video> element. As with the
former, there is no single codec which supported by all browsers (good choices are
mp3, wav, and ogg – but neither is supported by all four)
15
<audio><source src=“clip.ogg" type=“audio/ogg”/><source src=“clip.mp3" type=“audio/mp3”/><p>Your browser supports none of the codecs for this clip, or is not HTML5</p>
</audio>
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 and related technologies
The most impressive addition to HTML5 is that of the canvas element – which is really
just a blank placeholder: HTML5 itself has no drawing capabilities to speak of. A
canvas can simply be delcared as:
And that is all there is to it.
The trick, however, is to pair the canvas element with Javascript: Using Javascript, it is
easy to manipulate the blank canvas, and populate it with points, lines, curves and
images. The canvas exports a context through a getContext method, and it is in this
context that various drawing methods can be called (somewhat similar to the old
style LOGO programming language).
klists – as the link implies – unbelievable and impressive demos of this new element.
16
<canvas id="canvas" width=“1000" height=“1000"></canvas>
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 and related technologies
Another addition, not strictly part of HTML5 but supported by most of its browsers, is
Scalable Vector Graphics (SVG). This is an entirely self contained XML grammar,
specified in http://www.w3.org/TR/SVG/.
SVG is a tad difficult to use directly (though it has been, for example at
http://minding.hisown.biz/IMP/world.xml). Its true power is unleashed when
Javascript (technically, ECMAScript) is used to dynamically render it on the fly. A
simple but powerful visualization library called D3 (Data Driven Documents) is
available at http://www.d3js.org/, and some of its really cool samples are shown
below:
17
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 and related technologies
(C) 2013 Jonathan Levin, Technologeeks.com
18
(C) 2004, 2012 Technologeeks.com 19
CSS3(C) 2013 Jonathan Levin, Technologeeks.com
(C) 2004, 2012 Technologeeks.com 20
Cascading Style Sheets are the standard way to format HTML and XML elements.
Instead of individually formatting each element, leading to cumbersome tags, a
“stylesheet” may be introduced, with formatting rules. In fact, more than one style
sheet can apply to a document, and more than one style – to an element. Hence the
name “Cascading”. Each element inherits the style from the element(s) containing it.
CSS was developed in two “levels” – originally, there was the CSS1 draft. As it caught
on, CSS2 added new features and greater granularity (e.g, :hover) for display options.
CSS3 (currently in the works) further extends this standards with nifty effects such as
element opacity, and others.
To define stylesheets, either use a <STYLE> …. </STYLE> block or
<LINK rel=“stylesheet” type=“text/css” href=“…” /> to link to an external
stylesheet.
Styles themselves are defined in one of three ways:
• ELEMENTTYPE { style… }
(e.g. TD { cell-spacing : 10px ; cell-padding : 3px; } )
• .CLASS { style}
(e.g. .UnderlineText { text-decoration : underline })
• #ID { style }
( e.g. #contextMenu { border-color: #ff00ff ; font-size : 8pt; } )
CSS3(C) 2013 Jonathan Levin, Technologeeks.com
Note that classes must then be defined per element or per span (e.g. <SPAN
class=“CLASS”> …</SPAN>), and IDs – individually assigned to elements. This is still
better and more flexible than specifying the style per each element. Although this,
too, is legitimate, using the inline attribute STYLE=“ { } “.
For a comprehensive reference, refer to the W3C website
(http://www.w3.org/style/CSS). The W3C also have a CSS validator service, to check
conformity to the current standards.
(C) 2013 Jonathan Levin, Technologeeks.com
21
CSS3
(C) 2013 Jonathan Levin, Technologeeks.com
22
CSS3
A special note on conformance
(C) 2013 Jonathan Levin, Technologeeks.com
23
CSS3
(C) 2013 Jonathan Levin, Technologeeks.com
24
CSS3
(C) 2013 Jonathan Levin, Technologeeks.com
25
<!DOCTYPE html><html><head><title>Box Shadows</title><style>.shaded { border : 1px solid red;
border-radius : 15px ; box-shadow : 2px 2px 5px #aabbcc ;padding :10px; }
</style></head>
<body><div class="shaded">Lorem Ipsum</div></body></html>
CSS3
Assuming you have your TTF/OTF (or EOT, for IE9) font in place, specifying a custom
font is easy
(C) 2013 Jonathan Levin, Technologeeks.com
26
<!DOCTYPE html><html><head><style> @font-face{font-family: myCustomFont;src: url(‘custom.ttf'),url(‘custom.eot'); }div{ font-family: myCustomFont; }</style></head><body><div>Bringing my own font!</div></body></html>
CSS3
Example: Color all links to a site (say, Amazon.com) with a different color (red):
(C) 2013 Jonathan Levin, Technologeeks.com
27
<!DOCTYPE html><html><head></head><style>
a[href *="amazon"] { color : red }
</style><body><a href="dsssdf">test</a><a href="http://www.amazon.com/">Link to Amazon</a></body></html>
CSS3
Another good example site: http://cssmediaqueries.com/
(C) 2013 Jonathan Levin, Technologeeks.com
28
CSS3
(C) 2013 Jonathan Levin, Technologeeks.com
29
CSS3
(C) 2013 Jonathan Levin, Technologeeks.com
30
JavaScript Primer
31
(C) 2013 Jonathan Levin, Technologeeks.com JavaScript Primer
32
(C) 2013 Jonathan Levin, Technologeeks.com JavaScript Primer
33
(C) 2013 Jonathan Levin, Technologeeks.com JavaScript Primer
(C) 2013 Jonathan Levin, Technologeeks.com
34
JavaScript Primer
There are myriad javascript “frameworks” which can be used to simplify javascript
coding. Chief among those is Jquery, which has become ubiquitous and a de facto
standard, due to its very easy syntax.
It should be noted that frameworks do not really ADD any language features. They
are what is known as “syntactic sugar”: simplifying syntax using functions and
methods that are easier to use as one liners, rather than the underlying sequence of
javascript statements. In that sense, you can consider them much the same as C
macros.
(C) 2013 Jonathan Levin, Technologeeks.com
35
JavaScript Primer
(C) 2013 Jonathan Levin, Technologeeks.com
36
(C) 2004, 2012 Technologeeks.com 37
The Document Object Model (or DOM, for short), is indubitably the most powerful enhancement to Javascript. Scripts running in the context of an HTML (or XML) document can access each and every HTML element in the document, including the document object itself. This enables the runtime modification of element properties, paving the way to “DHTML” – Dynamic HTML.
It all begins with the “document” object, which is accessible by scripts executing in an HTML page. This powerful object exposes an incredible amount of methods and properties, which enable the runtime modification of any element on the page, or the document itself. For example, consider the following script:
As the example above illustrates, using document.write, it is possible to output text or HTML to the page, in runtime. A far more interesting case, involves re-writing HTML for already emitted elements, using getElementById, and the innerHTML property:
<HTML><BODY>Hello<SCRIPT>document.write (“<B>Hello, world!</B>”);</SCRIPT></BODY></HTML>
Listing 5-5: A simple example of the document object
(C) 2013 Jonathan Levin, Technologeeks.com Document Object Model
<HTML><DIV id="x">. . .</DIV><SCRIPT>varvarvarvar theDiv = document.getElementByIdgetElementByIdgetElementByIdgetElementById('x');/* Set the INNERHTML of the div – which will fill it with content */varvarvarvar s = "This is the DIV, as seen in DOM: " ;forforforfor (varvarvarvar prop inininin theDiv){ s+= prop + ":" + theDiv[prop] + "<BR/>";}
theDiv.innerHTMLinnerHTMLinnerHTMLinnerHTML = s;</SCRIPT></HTML>
(C) 2004, 2012 Technologeeks.com 38
(C) 2013 Jonathan Levin, Technologeeks.com Document Object Model
(C) 2004, 2012 Technologeeks.com 39
The DOM is best studied through “walking” it. Which is why the exercises presented
at the end of the chapter each focus on one or more specific aspects of it. The slide
above lists the reference and tools which may be used for DOM Programming.
It should be noted that IE and Mozilla have DIFFERENT DOM implementations. This is
why scripts are often checked (using navigator.appName or probing for document.all,
which only IE supports).
(C) 2013 Jonathan Levin, Technologeeks.com Document Object Model
(C) 2004, 2012 Technologeeks.com 40
Traversing the DOM is fairly simple, albeit a rather tedious task.
The loaded XML DOM object returns a reference to the top level document node. This is NOT
the root element of the document. Rather, it is a special node (of type “Document”), under
which the processing instructions as well as the actual root can be found.
To obtain the root element, loop over the “childNodes” array property of the document root.
One (and only one) child will be of nodeType “Element”. That’s the root.
(C) 2013 Jonathan Levin, Technologeeks.com Document Object Model
(C) 2004, 2012 Technologeeks.com 41
Each node has two important properties:
nodeType: an int value. The corresponding string type may be retrieved with the
nodeTypeString property. Node types may be “Document”, “Element”, “Text”, “Attribute”
(deprecated), “ProcessingInstruction”, “Comment”, “CDATASection”, “DocumentType”,
“Entity”, or “Notation”)
nodeValue: a string value, which may be “null” or empty, for nodes with no value.
Note, that ELEMENT nodes (nodeType == 1) have no value of their own. The value, if any, is
stored in a separate, child leaf node of type TEXT (nodeType == 3).
(C) 2013 Jonathan Levin, Technologeeks.com Document Object Model
(C) 2013 Jonathan Levin, Technologeeks.com
42
Document Object Model
(C) 2004, 2012 Technologeeks.com 43
Attributes are all leaf elements. To obtain their name/value pairs, note the example above.
Note in previous versions of DOM, the attributes were child nodes of their element parents.
CAVEAT: The “attributes” property MUST be checked to be not NULL! Othewise, your
javascript will fail with an error!
(C) 2013 Jonathan Levin, Technologeeks.com Document Object Model
(C) 2004, 2012 Technologeeks.com 44
It’s possible to traverse the DOM by focusing on a node, and using the properties shown
above to “zoom in” on its relatives.
Alternatively, it’s possible to search for Elements by their tag name.
(C) 2013 Jonathan Levin, Technologeeks.com Document Object Model
(C) 2004, 2012 Technologeeks.com 45
XML DOM can be used to create new DOM trees, on the fly.
-Create an Empty DOM tree
-Use CreateNode(), or one of the Create___ functions:
-CreateAttribute
-CreateCDATASection
-CreateComment
-CreateDocumentFragment
-CreateElement
-CreateEntityReference
-CreateProcessingInstruction
-CreateTextNode
-Finally, append to parent, using appendChild().
Use as many times as necessary.
(C) 2013 Jonathan Levin, Technologeeks.com Document Object Model
(C) 2004, 2012 Technologeeks.com 46
(C) 2013 Jonathan Levin, Technologeeks.com Document Object Model
(C) 2013 Jonathan Levin, Technologeeks.com
47
Now that the Javascript prerequisite has been sated, we can turn our attention to
other technologies, often grouped with HTML5, which require Javascript for
operation. Two of them, Canvas and Drag&Drop, are officially part of HTML5 – but
the rest are actually additions which exist almost solely in the Javascript space.
Because all HTML5 capable browsers support them, they are unofficially considered
part of HTML5 nowadays.
(C) 2013 Jonathan Levin, Technologeeks.com
48
HTML5 Scriptable Technologies
(C) 2013 Jonathan Levin, Technologeeks.com
49
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#dropTarget {width:100px;height:100px;padding:10px;border:1px solid black;}
</style>
<script>
function allowDrop(e) { e.preventDefault();}
function drag(e)
{ // Set custom field ("text") with drag target's ID, so we can later get it on drop
e.dataTransfer.setData("Text",e.target.id);
}
function drop(e)
{ e.preventDefault(); // handle this event ourselves
// Remember the data property we set? Here it is..
var data=e.dataTransfer.getData("Text");
// "move" the element by appending it to the drop target
e.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div id="dropTarget" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="dragMe" src="../e76/a.png" draggable="true" ondragstart="drag(event)" />
</body>
</html>
HTML5 Scriptable Technologies
(C) 2013 Jonathan Levin, Technologeeks.com
50
<meter value=“20" min="0" max="100">20 out of 100</meter>
HTML5 Scriptable Technologies
(C) 2013 Jonathan Levin, Technologeeks.com
51
HTML5 Scriptable Technologies
(C) 2013 Jonathan Levin, Technologeeks.com
52
HTML5 Scriptable Technologies
Web Storage started out as a part of the HTML5 specification, but has since been
spun off to its own specification. The idea is to allow web sites and applications to
store data on the local file system in a quarantined and safe manner. While cookies
offer some of that functionality, it can be abused to no end, and provides very limited
space to begin with (<4K in most browsers).
By contrast, web storage allows storage in the few megabytes (browser-dependent).
Storage can be accessed only through Javascript, and never gets sent over HTTP
traffic. The data stored is therefore for the client side use only.
As with cookies, web storage allows for session based and persistent storage. This is
maintained by two objects: the sessionStorage object and the localStorage object.
The storage objects are effectively dictionaries (keyed arrays), and operations on
them involve getting/setting items at given keys, or enumerating the keys (by treating
the storage object as a simple array, and querying its length property.
53
sessionStorage.setItem(‘key1', ‘value');var value = sessionStorage.getItem(‘key1');
localStorage.setItem(‘key2', ‘value2');var myVar = localStorage.getItem(‘key2');
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 Scriptable Technologies
Additionally, web storage offers a storage event, which comes in handy when multiple
instances of the same page are loaded in the browser (in separate tabs or windows).
This allows for other pages from the same site to be notified in real time that the data
in the storage has changed.
(C) 2013 Jonathan Levin, Technologeeks.com
53
By installing a event handler, a web page can be informed of which key changed, from
the oldValue to the newValue, as shown in the following example:
54
window.addEventListener('storage', function(event) {alert(“Storage changed at key “ + event.key + “: “
+ event.oldValue + “->” + event.newValue);
}
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 Scriptable Technologies
55
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 Scriptable Technologies
To check for web worker support, simply check if typeof (window.worker) is a
function.
A simple web worker example :
http://www.html5rocks.com/en/tutorials/workers/basics/
56
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 Scriptable Technologies
XMLHttpRequests have proven to be useful, but limited. WebSockets are a new
emerging standard, which enables full duplex communication between client and
server. This means that, unlike XHR, the server may initiate unsolicited messages to
the client – a useful feature for enabling chat, status reports, and other server-
generated communications. XHR would have forced a polling method, which is not
only inefficient, but places a significant load on both client and server.
57
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 Scriptable Technologies
Example:
58
(C) 2013 Jonathan Levin, Technologeeks.com
<script>
function wsErr (e){
alert(“Error: “ + e.data);}
function wsMsg (e){
alert (“Got message: “ + e.data);}var ws = new WebSocket (“ws://some.url”);ws.onopen = wsOpen;ws.onclose = wsClose;ws.onmessage = wsMsg;ws.onerror = wsErr;
ws.send (“Test”);
</script
HTML5 Scriptable Technologies
59
(C) 2013 Jonathan Levin, Technologeeks.com HTML5 Scriptable Technologies