Practical Web Applications

22 September 2011

[Prev][Next]

HTML, CSS, & JavaScript

Norman Walsh

MarkLogic Corporation

Agenda

Introduction

[Prev][Next]

Learning Objectives

[Prev][Next]

The language of the web, HTML, is getting the largest and most significant update perhaps in its entire history. The update includes both new features and new expectations of browser interoperability.

Modern web applications are built on three essential technologies:

  1. HTML

  2. CSS

  3. JavaScript

The role of HTML

[Prev][Next]

HTML(5) is the scaffolding. HTML5 brings:

  • Better interoperability

  • New semantic markup

  • New inlines

  • Better form controls

  • New ways of addressing mixed media

The role of CSS

[Prev][Next]

Cascading Style Sheets (CSS) are the skin:

  • Declarative style rules

  • Media-specific styling

The role of JavaScript

[Prev][Next]

JavaScript adds interactivity:

  • Dynamic behaviors in response to the user

  • “Application logic”

  • “Mashups”

  • Browsers provide APIs for additional functionality: geolocation, client-side storage, etc.

HTML

[Prev][Next]

Of HTML, XML, and SGML: A History

[Prev][Next]
  • Before there was XML, there was HTML. (And before that, SGML. And before that, …)

  • HTML (nominally SGML) and XHTML (XML) coexisted for a while.

  • HTML5 is not XML. It's not even nominally SGML.

HTML vs XML

[Prev][Next]
  • Philosophically, the differences are (mostly) about well-formedness and namespaces.

  • HTML is a language. XML is a language for creating languages.

  • Syntactically, the differences are (mostly) about error correction, browser interoperability, and author convenience.

    • <div><p>Some text</div> vs. <div><p>Some text</p></div>

    • <div id=myId>... vs. <div id="myId">...

    • <img src="pic.jpg"> vs. <img src="pic.jpg"/>

    • <video autoplay> vs. <video autoplay="autoplay">

HTML and XML revisited: Polyglot markup

[Prev][Next]

It is possible to compose documents such that they are “the same” whether you parse them with an HTML5 parser or an XML parser. Doing so requires following the “polyglot” rules:

  • Use namespaces for HTML, MathML, and SVG. Use only the default namespace (no prefixes)

  • Include html, head, title, and body elements

  • Include tbody in every table

  • Include colgroup if you're using col elements

  • Use exclusively lowercase except for a handful of SVG elements and attributes

  • Only empty element syntax for a specific list of elements.

  • Etc.

  • See Polyglot Markup: HTML-Compatible XHTML Documents

New HTML elements

[Prev][Next]

The following slides provide a survey of some of the new features introduced in HTML5.

  • article, header, section, footer

  • hgroup

<article>
  <header>
    <hgroup>
      <h1>Article Title</h1>
      <h2>Article subtitle</h2>
    </hgroup>
  </header>
  <p>Article content…</p>
  <section>
    <header>
      <h1>Section header</h1>
    </header>
    <p>Section content…</p>
  </section>
  <footer>
    <p>Footer content</p>
  </footer>
</article>

New HTML elements (continued)

[Prev][Next]
  • aside

  • nav

<body>
 <nav>
   <p><a href="/">Home</a></p>
 </nav>
 <p>Hello world.</p>
 <aside>
  <p>Some “sidebar” material</p>
 </aside>
</body>

New HTML elements (continued)

[Prev][Next]
  • details

<details open="open">
  <summary>Task summary</summary>
  <dl>
    <dt>Detail 1</dt>
    <dt>Detail 2</dt>
    <dt>Detail 3</dt>
  </dl>
</details>

New HTML elements (continued)

[Prev][Next]
  • figure and figcaption

<figure>
  <p>O for a Muse of fire, that would ascend<br/>
The brightest heaven of invention,<br/>
A kingdom for a stage, princes to act<br/>
And monarchs to behold the swelling scene!</p>
 <figcaption><cite>Henry V</cite> (Prologue).
 William Shakespeare.</figcaption>
</figure>

New HTML elements (continued)

[Prev][Next]
  • video and audio

  • track

<div>
<p><video src="funnyclip.webm" autoplay="autoplay"
          controls="controls" onerror="failed(event)">
  <track kind="subtitles" src="funnyclip.en.vtt"
         srclang="en" label="English"/>
  <track kind="subtitles" src="funnyclip.fr.vtt"
         srclang="fr" label="Français"/>
</video></p>
<p><a href="funnyclip.webm">Download the video</a>.</p>
</div>

(Many more options are available)

New HTML elements (continued)

[Prev][Next]
  • canvas

A canvas is a resolution-independent bitmap where JavaScript can render graphs, images, animation, etc.

<canvas xmlns="http://www.w3.org/1999/xhtml"
        id="mycanvas"/>

The game of Halma* Moves: 0

* Gleefully stolen from Mark Pilgrim's excellent Dive Into HTML5.

New HTML elements (continued)

[Prev][Next]
  • progress

    <progress xmlns="http://www.w3.org/1999/xhtml"
              id="progress" value="15" max="100">
    <span>15</span>%</progress>
    15%
  • meter

    <meter xmlns="http://www.w3.org/1999/xhtml"
           min="0" max="18" value="15">Size 15</meter>
    Size 15

New input types

[Prev][Next]

New type values for input tags in forms:

  • tel

  • search

  • datetime

  • datetime-local

  • date

  • month

  • week

  • number

  • range

  • email

  • url

  • time

  • color

Also:

  • autofocus on input

  • placeholder on input and textarea:

  • placeholder on input and textarea

  • required on input

Removed from HTML

[Prev][Next]
  • basefont, big, center, font, strike, tt

    Use CSS instead…

  • frame, frameset, noframes

    Use an iframe and CSS or compose the pages on the server…

  • acronym, applet, isindex, dir, … etc.

    Use abbr, embed or object, form, ul, … etc.

Plus lots of presentational attributes.

Interoperability

[Prev][Next]

What does all this new markup actually do?

When were you born?

<p xmlns="http://www.w3.org/1999/xhtml">When
were you born?
<input id="birthday" type="date" size="16"/>
</p>

Well, that depends.

Firefox 6.0

(Nothing)

Chrome 13.0.782.215

(A little up/down control)

Opera 11.50

(A full calendar widget)

Hands on

[Prev][Next]

Add “date” to the pub reviews.

The semantics question

[Prev][Next]
  • Web pages aren't just human-readable, they're also machine readable

  • Expressing semantics in a machine-understandable way is harder (more markup)

  • But the result (can be) clearer because the semantics are more explicit

  • If you're starting from rich XML sources, many of the semantics may already be manifest or implied

  • The trick is to encode them for web pages

Semantic quest

[Prev][Next]

Consider this example: you're looking for a kitten picture to put on your blog. You find this:

<img src="photo1.jpg" alt="An example photo" />

What might you need to know?

  • Who took it?

  • Is it licensed for reuse?

After all, the ones you can't reuse aren't very useful for your current task.

Ideally, if you could these questions machine understandable, you could filter on them.

Semantic examples

[Prev][Next]

RDFa:

<img src="photo1.jpg"
  rel="license"
  resource="http://creativecommons.org/licenses/by/2.0/"
  property="dc:creator" content="Mark Birbeck" />

HTML5/Microdata

<span itemscope="itemscope">
  <img itemprop="about" src="photo1.jpg">
  <link itemprop="http://www.w3.org/1999/xhtml/vocab#license" 
        href="http://creativecommons.org/licenses/by/2.0/">
  <meta itemprop="http://purl.org/dc/elements/1.1/creator" 
        content="Mark Birbeck">
</span>

This is a hot topic, I don't think the dust has fully settled yet.

Lights, camera, action!

[Prev][Next]

HTML5 vs. Flash vs. Silverlight

  • The canvas element and improved audio/video controls certainly make HTML+JavaScript a plausible competitor for Flash/Silverlight

  • Flash is not supported by the iOS platform

  • Flash and Silverlight are proprietary technologies.

  • All three techniques present accessibility challenges

Cascading Style Sheets (CSS)

[Prev][Next]

Cascading Style Sheets

[Prev][Next]

Associating style with elements:

code.red {
  background-color: #FFAAAA;
}

This means <code class="red"> has a red background color.

Cascading Style Sheets

[Prev][Next]

Associating style with elements:

And also something more complex:

span.ex > span:nth-child(2):before {
  content: " [ ";
  background-color: #AAFFAA;
}
span.ex > span:nth-child(2):after {
  content: " ] ";
  background-color: #AAFFAA;
}
<span class="ex"><span>first</span>,
<span>second</span>,<span>third</span>
</span>

renders like this: first,second,third

Adding CSS to HTML

[Prev][Next]

There are two ways to add CSS to an HTML page:

  • Inline:

    <style type="text/css">
    code.red {
      background-color: #FFAAAA;
    }
  • With a link:

    <link rel="stylesheet" type="text/css"
          href="css/webtech.css" />

CSS Selectors

[Prev][Next]
E

An “E” element

.cl

Any element with a “class” attribute that includes the class “cl”.

#id

Any element with an ID value of “id”.

CSS Selectors (continued)

[Prev][Next]
E.cl

An “E” element with a “class” attribute that includes the class “cl”.

E#id

An “E” element with the ID “id

A E

An “E” element that is a descendant of some ancestor “A

P > E

An “E” element who's parent is “P

P + E

An “E” element immediately preceded by a “P

CSS Selectors (continued)

[Prev][Next]
P ~ E

An “E” element preceded by a “P

E[a]

An “E” element with an “a” attribute.

E[a="val"]

An “E” element with an “a” attribute whose value is exactly “val”. (c.f. ~=, ^=, $=, *=, and |=)

CSS Selectors (continued)

[Prev][Next]
E:first-child

An “E” element that is the first child of its parent (c.f. :last-child, :first-of-type, :last-of-type, :only-child, and :only-of-type)

E:first-letter

The first (formatted) letter of an “E” element

E:first-line

The first (formatted) line of an “E” element

CSS Selectors (continued)

[Prev][Next]
E:empty

An “E” element that is empty

E:link (E:visited)

An “E” element that is a link that has not (has) been visited

E:active

An “E” element that is active (in a user action) (c.f. :hover, :focus, :enabled, :disabled, and checked:)

E:not(S)

An “E” element that does not match the simple selector “S

Hands on

[Prev][Next]

Add some style to pub finder.

CSS media queries

[Prev][Next]
  • In the modern world, are desktop and laptop machines, tablets, and mobile phones are all popular devices for accessing the internet. These have quite different aspect ratios and resolutions.

  • Designing for any one of those platforms is often straightforward. But creating a single design that works equally well on all those devices is exceedingly hard.

  • What we need is a way of selecting the appropriate design based on the device.

  • Enter media queries.

CSS media query examples

[Prev][Next]

Select the appropriate stylesheet:

<link rel="stylesheet" href="base.css"/>
<link rel="stylesheet" href="color.css"
      media="screen and (color)"/>
<link rel="stylesheet" href="print.css"
      media="print"/>
<link rel="stylesheet" href="phone.css"
      media="(max-width: 400px)"/>
<link rel="stylesheet" href="landscape.css"
      media="handheld and (orientation:landscape)"/>

Or select the appropriate rule:

@media screen and (device-aspect-ratio: 16/9) {
  /* 16x9 device rules */
}

JavaScript

[Prev][Next]

JavaScript

[Prev][Next]
  • JavaScript is the defacto standard programming language for web applications; browsers expose significant JavaScript APIs (n.b.: it is also popular in other contexts)

  • Although it started as a slow, limited, odd little language, it has grown into a quite substantial and robust (if still a bit odd) language supported on some very fast virtual machines

  • Technically, it is an object-oriented language that uses prototypes; it is a dynamic language with first-class and nested functions supporting closures

  • JavaScript utilizes (or supports) a mixture of object-oriented, imperative, and functional programming styles

  • Syntactically, it's from the C/Java school

JavaScript Syntax

[Prev][Next]

In lieu of several hours of JavaScript instruction…some examples

/* comment */
return 3+4;

var x = 3;
var y = 4;
return x+y // 7, in case you weren't sure

function f(n) {
  var total = 0; // local variable
  total += n;
  return total;
}

JavaScript Syntax (continued)

[Prev][Next]
// More examples

var produce = { "apple":      { "color": "red",
                                "fruit": true },
                "plum":       { "color": "purple",
                                "fruit": true },
                "strawberry": { "color": "red",
                                "fruit": false } };

produce["plum"]["color"] // "purple"
produce.strawberry.fruit // false

return obj.b().c()

JavaScript and CSS

[Prev][Next]

Combining JavaScript and CSS makes interactive applications easy and efficient.

  • Respond to events (user input, mouse motion, server actions)

  • Locate HTML elements in the browser

  • Update the CSS associated with those elements (highlight, hide, show, move, resize, etc.)

JavaScript and AJAX

[Prev][Next]

One of the things that reinvigorated interest in JavaScript a few years ago was the (re)discovery of AJAX: “Asynchronous JavaScript and XML”.

  • JavaScript running in the browser send an HTTP request to a server.

  • It establishes a callback function for the result and returns control to the browser.

  • When the server responds, the callback function is automatically called

  • This leads to fast, dynamic applications

JavaScript and JSON

[Prev][Next]

Many AJAX services these days use JSON instead of XML:

{
    "name": {
        "first": "John",
        "last": "Smith"
    },
    "age": 45,
    "phones": [
        "+1-413-555-1212",
        "+44-1603633522"
    ]
}
  • JSON encodes simple data values: objects (hash tables), arrays, numbers, strings, boolean “true”, boolean “false”, and “null”.

  • Objects and arrays can be nested

  • This syntax fits naturally into the JavaScript programming language

  • JSON offers no practical way to represent mixed content

JavaScript Frameworks

[Prev][Next]

JavaScript frameworks offer many advantages:

  • Conceal browser differences

  • Offer APIs more consistent with JavaScript programming

  • Provide syntactic conveniences (by using the underlying prototype nature of JavaScript's object system to extend the language)

Use a framework.

Popular JavaScript Frameworks

[Prev][Next]
  • Dojo

  • jQuery

  • MochiKit

  • Prototype/script.aculo.us

  • YUI

See Comparison of JavaScript frameworks.

In the examples that follow, I'll be using jQuery.

Unobtrusive JavaScript

[Prev][Next]

The name “unobtrusive javascript” is a label for a set of best practices.

  • Keep your JavaScript out of your HTML.

  • Fail gracefully.

  • Don't interfere with accessibility: deliver useful information even in the face of missing or failing JavaScript.

Let's consider an example…

Unobtrusive Example

[Prev][Next]

The name “unobtrusive javascript” is a label for a set of best practices.

<div class="details">
  <div class="title">Be unobtrusive</div>
  <ul>
    <li><p>Keep your JavaScript out of your HTML.
    </p></li>
    <li><p>Fail gracefully.</p></li>
    <li><p>Don't interfere with accessibility</p>
    </li>
  </ul>
</div>
Be unobtrusive
  • Keep your JavaScript out of your HTML.

  • Fail gracefully.

  • Don't interfere with accessibility.

Unobtrusive Example (continued)

[Prev][Next]

The name “unobtrusive javascript” is a label for a set of best practices.

Be unobtrusive
  • Keep your JavaScript out of your HTML.

  • Fail gracefully.

  • Don't interfere with accessibility.

Unobtrusive Example Explained 1/4

[Prev][Next]

HTML:

<head>
  ...
  <script type="text/javascript"
          src="js/jquery-1.6.2.min.js"></script>
  <script type="text/javascript"
          src="js/webtech.js"></script>
</head>

Unobtrusive Example Explained 2/4

[Prev][Next]

JavaScript:

$(document).ready(function(){
    beUnobtrusive();
});

function beUnobtrusive() {
    // If we get here, we have JavaScript and JQuery. Duh.
    $("div.details").each(processDetails);
}

function processDetails() {
    $(this).children("div").each(processDiv);
}

function processDiv() {
    $(this).css("font-weight", "bold")
        .addClass("toggleClosed")
        .click(toggleList);
}

function toggleList() {
    $(this).toggleClass("toggleClosed")
        .toggleClass("toggleOpen");
}

Unobtrusive Example Explained 3/4

[Prev][Next]

CSS:

.toggleClosed:before {
    content: "\25B6 ";
}

.toggleOpen:before {
    content: "\25BC ";
}

.toggleClosed ~ ul {
    display: none;
}

Unobtrusive Example Explained 4/4

[Prev][Next]

Alternate JavaScript:

function beUnobtrusive() {
    // If we get here, we have JavaScript and JQuery. Duh.
    $("div.details").each(function() {
        $(this).children("div").each(function () {
            $(this).css("font-weight", "bold")
                .addClass("toggleClosed");
            $(this).click(function() {
                $(this).toggleClass("toggleClosed")
                    .toggleClass("toggleOpen");
            });
        });
    });
}

Alternate Example

[Prev][Next]
<details xmlns="http://www.w3.org/1999/xhtml">
  <summary>Be unobtrusive</summary>
  <ul>
    <li><p>Keep your JavaScript out of your HTML.
    </p></li>
    <li><p>Fail gracefully.</p></li>
    <li><p>Don't interfere with accessibility</p>
    </li>
  </ul>
</details>
Be unobtrusive
  • Keep your JavaScript out of your HTML.

  • Fail gracefully.

  • Don't interfere with accessibility

Progressive enhancement

[Prev][Next]

Remember our birthday example?

<p xmlns="http://www.w3.org/1999/xhtml">When
were you born?
<input id="birthday" type="date" size="16"/>
</p>

Try it out:

When were you born?

Progressive enhancement: How?

[Prev][Next]
<head>
  ...
  <link type="text/css"
        href="css/ui/jquery-ui-1.8.16.css"
        rel="stylesheet" />
  <script type="text/javascript"
          src="js/jquery-ui-1.8.16.min.js"></script>
  <script type="text/javascript"
          src="js/webtech.js"></script>
</head>

js/webtech.js:

$(document).ready(function(){
    var datetest = document.createElement("input");
    datetest.setAttribute("type", "date");
    if (datetest.type == "text") {
        // This browser doesn't support the date type
        $("#birthday").datepicker(
          { dateFormat: "yy-mm-dd" }
        );
    }
});

“Modernizing” Toolkits

[Prev][Next]
  • Supporting the date input type was a good example of progressive enhancement, but in reality you don't have to code it yourself.

  • There are toolkits for exactly this purpose.

JavaScript APIs

[Prev][Next]
  • Geolocation

  • Client-side storage

Geolocation API

[Prev][Next]
  • The Geolocation API is part of HTML5 and answers the question “where are you?”

  • Many mobile devices have a GPS. Desktop and laptop browsers may be able to use other mechanisms (IP address, nearby wifi access points)

  • Recent browsers support the standard, older browsers may have proprietary APIs.

  • Getting a users geolocation requires their consent.

Welcome to Oxford

[Prev][Next]

Where are you?

Geolocation API

[Prev][Next]
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        updateGeo, handleError);
}
function updateGeo(position) {
    alert("You are here: "
          + position.coords.latitude
          + "," +  position.coords.longitude);
}
function handleError(err) {
    alert ('It all went terribly wrong.');
}

Hands on

[Prev][Next]

Add geolocation to pubfinder.

Local storage

[Prev][Next]
  • HTML5 Web Storage is a simple API for storing data locally

  • Think about applications that you might want to run when you're disconnected.

  • If they can store data locally, they may be able to restart without a net connection.

Local storage API

[Prev][Next]

There are just three things to know:

  • Missing API: typeof localStorage === "undefined"

  • Save a value: localStorage.setItem("key", value)

  • Retrieve a value: localStorage.getItem("key")

It is possible to run out of storage, so some error checking is also in order.

What about my code?

[Prev][Next]

Local storage of data is fine, but how do I save my HTML, JavaScript, CSS, images, and other files locally?

  1. Add a manifest to your html element:

    <html manifest="myapp.appcache">
       ...
  2. Create a manifest file, myapp.appcache listing the files that you want to have cached locally:

    CACHE MANIFEST
    app.html
    app.js
    app.css
    images/banner.png
  3. Make sure that the manifest is served with the media type “text/cache-manifest”.

Q&A

[Prev][Next]

Thanks!