0% found this document useful (0 votes)
36 views

HTML Avancer

The document discusses changes made in HTML5 that simplify its usage. Key changes include making the doctype definition a single line "<!DOCTYPE html>", making attributes like "type" optional, and relaxing syntax constraints. HTML5 also added new structural elements based on common elements found during analyses of over a billion web pages, like <header>, <footer>, <nav>, <article>, and <section>.

Uploaded by

mahad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

HTML Avancer

The document discusses changes made in HTML5 that simplify its usage. Key changes include making the doctype definition a single line "<!DOCTYPE html>", making attributes like "type" optional, and relaxing syntax constraints. HTML5 also added new structural elements based on common elements found during analyses of over a billion web pages, like <header>, <footer>, <nav>, <article>, and <section>.

Uploaded by

mahad
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 136

Changes have been made 

to particular elements in HTML5 making it simpler to use. In this


section, we will look at some examples highlighting these improvements, including:
o the new doctype definition;
o the fact that the "type" attribute of elements such as <link> or <script> are now  optional;
o the syntax constraints that have been relaxed;
o the new structural elements that have been added, etc.
A minimal HTML5 document

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4.    <meta charset="utf-8">
5.    <title>Page Title</title>
6.    <link rel="stylesheet" href="style.css">
7.    <script src="script.js"></script>
8. </head>
9. <body>
10. ... <!-- The rest is content -->
11. </body>
12. </html>

Let's compare it to the HTML4 minimal document below (taken from this source).
Differences are underlined in red:

1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"


"https://www.w3.org/TR/html4/strict.dtd">
2. <html lang="en">
3. <head>
4.     <meta http-equiv="content-type" content="text/html" charset="utf-8">
5.     <title>title</title>
6.     <link rel="stylesheet" type="text/css" href="style.css">
7.     <script type="text/javascript" src="script.js"></script>
8. </head>
9. <body>
10. ...
11. </body>
12. </html>
Simpler character set definition
One word about the <meta charset="utf-8"> at line 4 in the HTML5 version: it
is a best practice to declare the character set of your document to protect against a
serious security risk. For more details, please refer to the "Why Internationalization is
important" section in the Course intro chapter.
No more complicated DOCTYPE definitions
The "DOCTYPE" (Document Type Declaration) is used by tools such as HTML
validators (i.e.  the W3C validator), and specifies the rules used by  an HTML or an
XHTML page. These rules are contained in special documents called "Document
Type Definitions" (also abbreviated as DTDs), written in a language that may seem a
bit barbaric to humans (they are intended to be read by software), and hosted by
W3C.

DTDs are not used by current Web browsers to  validate the structure of an HTML
page, as  they "read" the code without using the DTD to decipher it, using only "rules"
contained in their own "HTML engine", but it is still preferable to indicate the doctype as
modern browsers have several rendering engines that are chosen depending on the doctype.

Old HTML1 Web pages will not be rendered the same way as new HTML5 pages,
since, in the 90's, some of them were written by hand and may contain errors,
embedded HTML elements, etc.

With HTML4, doctype definitions looked like this: <!DOCTYPE HTML PUBLIC


"-//W3C//DTD HTML 4.01 Transitional//EN"
"https://www.w3.org/TR/html4/loose.dtd">, which was even more
complicated as one had to choose between three different possibilities (doctypes
could be transitional, strict, or frameset). Most of the time, the doctype definition was
copied and pasted from one document to another and was nearly impossible to
memorize.

With HTML5, there is only one way to indicate the doctype, and it's so simple there is
no reason to forget it:

1. <!doctype html>
The "TYPE" attribute is optional
With a rel="stylesheet" attribute, it is no longer necessary to
indicate type="text/css" (from the specification: "the default type for resources
given by the   stylesheet   keyword is text/css.")

The "type" attribute is not needed in HTML5, and even old browsers will use text/css
as the default type for stylesheets today. So, either way, you can omit the "type"
attribute altogether and use:

1. <link href="file.css" rel="stylesheet"/>

instead of:

1. <link href="file.css" rel="stylesheet" type="text/css"/>
We will not go into detail about the <link> element, but the fact that
the type attribute is becoming optional shows the current direction taken by HTML5:
towards greater simplicity.

Please see how to include a JavaScript file in our page:

1. <script src="script.js"></script>

Here again, the type attribute has been omitted. Just as a reminder, the old way to do
the same thing is: 

1. <script type="text/javascript" src="script.js"></script>
More flexible syntax constraints
If you look at the "minimal document" example, or at other examples in this course,
you won't find a lot of differences compared to the same code in XHTML: attribute
values are surrounded by quotes, all elements are written in lower case, etc. This is
because we are used to writing this way, but HTML5 also supports a simplified
syntax:

 Thanks to HTML5, you can omit quotes (not always, but most of the time) or use
uppercase, lowercase or a combination of the two.

 Many elements no longer need a closing tag: </li>, </dt>, </dd>, </tr>,


</th>, </td>, </thead>, </tfoot>, </tbody>, </option>,
</optgroup>, </p> (in most cases), </head>, </body> and </html>. Older
browsers often add closing tags automatically at render time. We recommend,
however, closing tags that would naturally be closed: the ones that delimit a
particular zone in the document.

 Attribute values only need to be quoted if they contain spaces or some non-
alphanumeric characters, instead of
writing <link rel="stylesheet" href="style.css">, we could have
used <link rel=stylesheet href=style.css>. However, for compatibility with
older browsers, it is wiser to still use quotes...

Knowledge check 1.3.1 (not graded)


0 points possible (ungraded)
Did you read this page? Aha, let's check!

What is the minimal code to define DOCTYPE in HTML5?


1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"


"http://www.w3.org/TR/html4/strict.dtd">

1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01


Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

1. <!DOCTYPE html>
New structural elements

History
As Web site layouts evolve, HTML5 structural elements such as lists, paragraphs,
tables, etc. show their limits. Today, many Web sites offer navigation menus, tabbed
panels, headers, footers, and so on. The way these "parts"' are implemented relies
heavily on <div> and <span> elements with different id and class attributes, lots of
CSS and lots of JavaScript code to apply custom styles and behaviors.

However, there are some issues with this approach:

o id and class names differ from one developer to another, from one country to another, etc.

o Even with the same ids and class names, the css rules may be different

o JavaScript libraries have become increasingly heavy over the years

o Web pages have become increasingly heavy over the years!

o These elements can not be handled by the Web browser natively...

Even if differences exist between ids, classes and css/js implementations, they also
share common behaviors, layouts, and "ways of doing things" that could be guessed
at first glance by a human.

So various studies have been conducted in order to identify the most popular ids,
class names, widgets, etc. used on the Web:

Quoting from this article: "During the creation of HTML5, Ian Hickson used Google's
tools to mine data from over a billion Web pages, surveying what ids and class
names are most commonly used on the real world Web. Opera did a similar study of
3.5 million URLs, calling it MAMA ("Metadata Analysis and Mining Application").
MAMA, as structural Web-paged search engine, had a smaller URL set, but looked at
a larger and wider variety of Web page statistics".

New elements added to the HTML5 set


The results of these surveys led to the addition of new structural elements in HTML5.
For example, the very popular <div class="header"> led to the creation of
a <header> element, <div class="aside"> to a <aside> element, etc.

Finally, the 20 most popular ids and class names found in Hickson's and Opera's
surveys gave birth to these new elements (click on the element's name to go to the
W3C specification about this element):

HTML5 structural elements with descriptions.

HTML5 element Description


Introduction of "sectioning elements": an article, a section, the entire
document (header page). Typically the header of a Web site that appears
on top of each page, or a header of a long <article> or of a
long <section>
<header>

Contains the footer of a site, a long <article>, or a


long <section>
<footer>

Section that contains the main navigation links (within the document or
to other pages).
<nav>

Independent content, which can be individually extracted from the


document and syndicated (RSS or equivalent) without penalizing its
understanding. Typically a blog post.
<article>

Generic section used to group different articles for different purposes or


subjects, or to define the different sections of a single article. Generally
used with a header.
<section>

Used for marking up times and dates.


<time>

Section whose content is not necessarily directly related to the main


content that surrounds it, but can provide additional information.
<aside>

Used to encapsulate a figure as a single item, and contains a caption for


the figure, respectively.
<figure> and <figcaption>
The main element represents the main content of the body of a document
or application. The main content area consists of content that is directly
related to or expands upon the central topic of a document or central
functionality of an application. There can be only one <main> element
in a document.
<main>

And there is no <content> element even though the <div


class="content"> was very popular. Instead, the HTML5 group decided that
anything not embedded in one of the elements from the above table is "default
content". If the content is of a type that corresponds to one of the elements from the
table, i.e. if the content is an article, it should be embedded
between <article> and </article>.

Read also at the end of this section about the new <main> element .  This element
is part of the HTML5 recommendation and  an integral part of the HTML document
structure.

External resources:

 A Smashing Magazine article: Structural Semantics: The Importance Of HTML5 Sectioning


Elements

 A Dev. Opera article: New Structural Elements in HTML5

Knowledge check 1.3.2 (not graded)


0 points possible (ungraded)

Which of the following is not a structural element in HTML5?

nav

footer

title

header

Use a <header> at the top of the blog

This is an example of one way to organize a blog. Here, we have designed the HTML
page using a <header> element that contains the "Simple HTML5 blog" text that
appears on top of the page.
HTML code:

1. <!DOCTYPE html>

2.    <html lang="en">

3.       <head>

4.          <meta charset="utf-8"/>

5.          <title>Simple HTML5 blog</title>

6.       </head>

7.       <body>

8.          <header>

9.             <h1>Simple <span>HTML5</span> blog</h1>

10.          </header>

11. ...

The CSS rules we used:

1. header {

2.     color: #007e99;

3.     font-size: 2.5em;

4.     padding: 20px 50px

5. }

6. header span {

7.     color: #722

8. }
Use a <nav> for the navigation menu just below the header
The navigation menu just below the header is a <nav> element. For the purpose of
this example we haven't provided any value for the hyperlinks...

HTML code:

1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4.    <meta charset="utf-8"/>

5.    <title>Simple HTML5 blog</title>

6. </head>

7. <body>

8. <header>

9.    <h1>Simple <span>HTML5</span> blog</h1>

10. </header>

11. <nav>

12.     <ul>

13.        <li><span>Blog</span></li>

14.        <li><a href="">About</a></li>

15.        <li><a href="">Contact</a></li>

16.     </ul>

17. </nav>

And here is the CSS we used in this example for the <nav> element:

1. nav {

2.     font-size: 1.5em;
3.     margin: 5px 0;

4.     padding: 20px 50px

5. }

6. nav li {

7.     display: inline;

8.     margin: 0 15px

9. }

10. nav li:first-child {

11.     margin-left: 0

12. }

13. * html nav ul {

14.     margin-left: -15px

15. }

16. nav span, nav a {

17.     padding: 3px 15px 4px

18. }

19. nav span {

20.     background: #722;

21.     color: #fff

22. }
A <section> for each month and an <article> for each post in the blog

Now, we have one big <section> element that contains a set


of <article> elements...
HTML code:

1. <section>

2.

3.    <article>

4.     ...

5.    </article>

6.

7.    <article>

8.     ...

9.    </article>

10.

11.    <article>

12.     ...

13.    </article>

14.

15. </section>
And here is the CSS:

1. section {

2.    float: left;

3.    padding: 35px 0;

4.    position: relative;

5.    width: 70%

6. }

7. section article {

8.    margin: 0 50px 40px;

9.    padding: 25px 0 0;

10.    position: relative

11. }

12. section header {

13.    font-size: 1em;

14.    padding: 0;

15. }

16. section h2 {

17.    font-size: 2.3em;

18. }

Note that the H2, article, article header, etc. will be styled using these rules.
Add a <header> at the beginning of each <article>

Next, in each article in the section we have a header (to display the article title),
paragraphs (article content), and so on.

Example for the first blog article:

1. <section>

2.    <article>

3.      <header>

4.          <h2><a href="">Information about this example</a></h2>

5.      </header>

6.

7.      <p>Try to move the mouse on different elements. The structure will be

8.      highlighted and you will be able

9.      to see the different inclusions of elements one in each other. If you

10.      move the cursor to this sentence, it will be highlighted in dark grey,

11.      showing the presence of an &lt;article&gt; element, surrounded by a

12.      &lt;section&gt; element (light grey), etc. So we have some articles in

13.      a single section element. The page title at the top is a &lt;header&gt;

14.      element, while the tag cloud on the right is a &lt;aside&gt; element. The

15.      main menu on top (with Blog, About, Contact) is a &lt;nav&gt; element.</p>


16.

17.      <figure>

18.          <img src="HTML5-tags.png"

19.              alt="Example of HTML5 structural tags" />

20.          <figcaption>

21.              Fig. 1 : an example of how new structural elements could

22.              be used. This page put a &lt;nav&gt; on top, and does not have

23.              headers and footer for each article, like in


this figure,

24.              but it could... By the way this is a

25.              &lt;figcaption&gt; inside a &lt;figure&gt; element...

26.          </figcaption>

27.     </figure>

28.

29.    </article>

30.    ...

31. </section>
Use <figure> and <figcaption> and embed <img> inside

Also note the way we included a figure using the new "HTML5" method, using
a <figure>..</figure> element that embedded a <img src=.../> element
together with a <figcaption> element. 
Here is the CSS for the <figcaption> element we have used in the example (we
did not apply any style to the <figure> element):

HTML code:

1. <figure>

2.     <img src="HTML5-tags.png"

3.          alt="Example of HTML5 structural tags" />

4.     <figcaption>

5.         Fig. 1 : an example of how .....

6.     </figcaption>

7. </figure>

CSS code:

1. figcaption {

2.     font-style:italic;

3.     font-size: 0.8em;
4.     width: 100%

5. }
Use an <aside> element to display a tag cloud on the... side of the main content

After the long <section> element that contains all the blog articles displayed in the
page, we added the HTML code for the tag cloud that is displayed on the right of the
page, "aside"! This is done using - you already guessed it - an <aside> element:

1. <section>

2. .... all <article>... </article> here....

3. </section>

4. <aside>

5.    <h2>Tag cloud</h2>

6.    <ul class="tag-cloud">

7.        <li><a href="" rel="tag" class="w2">ajax</a></li>

8.        <li><a href="" rel="tag" class="w8">apple</a></li>

9.        <li><a href="" rel="tag" class="w3">css</a></li>

10.        ...

11.    </ul>

12. </aside>
13. ...

We are not going to show the complete CSS here as it uses some tricks to display
the list as a "real tag cloud" that uses JavaScript for handling events, etc. Those who
are curious can look at the code of the online example.

Here is the CSS for the <aside> element:

1. aside {

2.     float: right;

3.     padding: 70px 0 30px;

4.     position: relative;

5.     width: 25%

6. }

7.

8. aside h2 {

9.     color: #888;

10.     font-size: 1.8em

11. }

12. aside .tag-cloud {

13.     padding: 15px 35px 10px 0;

14.     text-align: center

15. }

16. ...

We used a float:right CSS rule to put the tag cloud on the right... In a following
section we will provide several examples that explain how to make a nice layout with
the new structural elements, using simple CSS rules.

Here is the result:


Add a <footer> at the end of the blog

Finally, we added a <footer> element (lines 12-14 below) after the tag cloud


definition, to display a page footer:

1. <html>

2. ...

3. <body>

4. ...

5. <section>

6. ...

7. </section>

8. <aside>

9. ...

10. </aside>
11.

12. <footer>

13.    <p>&copy; 2009 Some blog</p>

14. </footer>

15.

16. </body>

17. </html>

With this CSS rule:

1. footer {

2.     clear: both;

3.     color: #777;

4.     padding: 10px 50px

5. }

And here is the result at the bottom of the page:

Knowledge check 1.3.3 (not graded)


0 points possible (ungraded)

What is a figcaption?

An image link
A caption under a figure

A tool for catching figs

A tool for taking a selfie

Can an <article> contain a <section>?

It may not be clear whether a <section> may contain one or


several <article> elements or if an <article> may contain one or
several <section> elements.

o The <article> element was designed for stand-alone parts of a document that could


eventually be syndicated in RSS streams.

o <section> elements are used to cut a logical part into subparts.

An <article> may be cut into different <section> elements!

Example of a blog post defined as a long <article>, that is in turn cut into


smaller <section> elements:

1. <article id="id1">
2.
3.    <section id="id1part1">
4.      <h2>Introduction</h2>
5.    </section>
6.
7.    <section id="id1part2">
8.      <h2>My travel to India</h2>
9.    </section>
10.
11.    <section id="id1part3">
12.      <h2>Return to France</h2>
13.    </section>
14.
15. </article>
The blog example from the previous part of the course, on the other hand, uses a
single <section> that contains several <article> elements.

Indeed, we can also have a <section> that regroups all blog posts per month, each
one being an <article> element.

A <section> may be cut into different <article> elements, too!

Can you put a <nav> in an <article>?


Yes you can, in case you would like to propose some navigation links with each blog
post, for example:

1. <article>
2.    <header>
3.      <h1>Blog post title</h1>
4.        <p>Author: Michel</p>
5.    </header>
6.    <nav>
7.        <ul>
8.            <li><a href="...">Next post</a></li>
9.            <li><a href="...">Previous post</a></li>
10.            <li><a href="...">Contact author</a></li>
11.        </ul>
12.    </nav>
13.    <p>Content...</p>
14.    <footer>
15.      <p>Posted by Michel, the <time datetime="2012-02-02">February 2,

16.      2012</time> </p>
17.    </footer>
18. </article>

In  that case, the <nav> element proposes navigation links to the next or previous


blog post, as well as a link to contact the author of the blog post.

Also note that we used in that example a <footer> element in the blog post.

What about the <div> element? Is it still useful?


The new elements have been primarily designed to better structure the code of
HTML pages such as those generated by blog or CMS software, however do not
forget that they add new semantics and will be taken into account by :
o Browsers natively or browsers' extensions, i.e. for automatically generating a table of
contents, an outline view of the document, for applying default CSS rules to these elements,
etc. See for example the table-of-contents-crx extension (Chrome extension). More on that in
the next section of the course.

o Text to speech: https://www.w3.org/WAI/perspective-videos/speech/

o Web crawlers, etc.

You can use <div> elements in all cases where the proposed structural elements do
not fit your needs: for defining some content that should be styled, for example.

This chart from the HTML5 Doctor Web site may help you decide whether or not to
use a <div>:

Knowledge check 1.3.4 (not graded)


0 points possible (ungraded)
Can a section contain an article?
Yes
No
non répondu
Use <h1>...<h6> for the headings
Since the very beginning, HTML has had heading elements: <h1>...<h6>. These
elements are used to display headings with different sizes by default, when no CSS
is used.  The following example shows 6 sentences that are surrounded by <h1>,
<h2>, <h3>, <h4>, <h5> and <h6>:

This is a H1 heading

This is a H2 heading
This is a H3 heading
This is a H4 heading

This is a H5 heading

This is a H6 heading

These headings define a hierarchy, as shown by the default sizes given by the
browser. This hierarchy can also be used to define an outline of the document. To
illustrate this, we have used a browser extension. Here is the result for the previous
example:

In the above outline, note that we have only used H1... H6 elements, without any new
HTML5 structural elements such as <section> or <article>.
Here is a list of browser extensions you can try, for visualizing the outline of a
document: table-of-contents-crx Chrome extension or this Firefox extension.

Using headings and new sectioning elements (section, article,


aside, nav)
Definition of heading content and sectioning content
The <section>, <article>, <nav> and <aside> elements are
called "sectioning elements". They cut a document into slices we call "sections".

The HTML5 specification says that "each sectioning element potentially has a
heading and has also an outline associated".

<h1>...<h6> are called headings, and define the header of a section (whether


explicitly marked up using sectioning content elements, or implied by the heading
content itself). This means that:

1. <body>

2.     <h1>Title of my document</h1>

3.     ...

4. </body>

... defines the header of a section implicitly, while:

1. <body>

2.    ...

3.    <section>

4.       <h1>Title of my section</h1>

5.       ...

6.    </section>

7. </body>

... defines the heading of the explicit section (its parent element <section>).

Use multiple headings of different rank with sectioning content


The first element of a heading content in an element of sectioning content represents
the heading for that section (the <section><h1>...</h1></section> in the
above example).

Subsequent headings of equal or higher rank start new (implied) sections, headings
of lower rank start implied subsections that are part of the previous one. In both
cases, the element represents the heading of the implied section.

Let's clarify this by looking at some example code:

1. <body>

2. <section>

3.     <h1>This H1 is the heading of an explicit section</h1>

4.     ...

5.        <h2>This H2 is a subheading, part of the same section

6.            (lower rank)</h2>

7.             ....

8.     <h1>This H1 starts an implicit new section in the explicit

9.         section (equal or higher rank)</h1>

10.         ...

11.         <h2>This is a H2 heading in the new section that has

12.             just started</h2>

13.             ...

14. </section>

15. </body>

The corresponding outline is:


 In the above example, please note two things:

1. The outline shows an "Untitled body" at the root of the hierarchy,

2. The default size for the H1 and H2 is the same (!). Indeed, when we start a <h1> inside
a <section> the browser lowers its default size automatically, as if a new hierarchy level
has been added artificially. We will discuss this further in the following sections, as we
introduce some best practices.

Knowledge check 1.3.5 (not graded)


0 points possible (ungraded)

Before HTML5, how many levels of headings were avalaible?

Best practice #1: always add a heading to explicit sectioning


content
It's always better - mainly for accessibility reasons - to include a heading (a <h1>,
<h2>...<h6>) in each sectioning element (<section>, <article>, <nav>,
<aside>), but also after the <body> element (called a "sectioning root"). 

Here are some examples:

Good (heading in each explicit section):


1. <section>

2.     <h1>Blog post of April 2020</h1>

3.     ...

4. </section>

Good (heading  in a <header> does not change anything)

1. <section>

2.    <header>

3.       <h1>Blog post of April 2020</h1>

4.       <p>Posted by Michel Buffa...</p>

5.    </header>

6. ...

7. </section>

Bad (there is no Hx after the <section> -> no heading):

1. <section>

2.    <header>

3.       <p class="article title">Blog post of April 2020</p>

4.       <p>Posted by Michel Buffa...</p>

5.    </header>

6.    ...

7. </section>

The last example is bad for accessibility reasons. A screen reader that vocalizes the
page will just say "Entering section", while in the previous two good examples it
would say "entering section with heading Blog Posts of April 2020". You can also
check if your headings and sectioning elements are ok by using a browser extension
that displays the outline of the document (just search for "html5 outliner" in your
browser's extension search engine).

UPDATE : For the course screenshots, we used the Google Chrome HTML5
outliner extension that is no more available (it has been removed by its developer),
but you can use any other equivalent extension such as table-of-contents-crx for
Chrome or Outline sidebar for Firefox.

The outline of the last example looks like this:

Notice that <body> is also a sectioning element. It's called a "sectioning root", and
would also need a heading.

Final good version:

1. <body>

2.     <h1>Example Blog</h1>

3.     <section>

4.        <header>

5.           <h2>Blog post of April 2020</h2>

6.           <p>Posted by Michel Buffa...</p>

7.        </header>

8.       <p>Content of the blog post...</p>

9.    </section>

10. </body>
In red, the sectioning root (<body>) and the sectioning elements
(<section> here...), each have a heading.

To sum up:

o Always use a heading element after a sectioning element, for


example <section><Hx>...</Hx>...</section>, and after <body>, where x can
be 1..6,

o Or, use a <header> element, like


in <section><header><Hx>...</Hx>.....</header>...</section>

More about the <header> element

The <header> element is just a container. It is not taken into account for


defining new sections of a document nor does it affect the hierarchy levels. 

You can use heading elements <h1>...<h6> in a <header> but be careful if you


use more than one, as the rules explained in the previous part of the course will
apply and may generate implicit "sections" in the header.

This example has two headings in the <header>:

1. <section>

2.    <header>

3.      <h1>Some text in a h1 in a header of a section</h1>

4.      <h2>This a h2 in the header...</h2>

5.    </header>

6. </section>

Here is the resulting table of contents, notice the two subsections that appear, one
for the H1, one for the H2:

Indeed, HTML does not have a dedicated mechanism for marking up subheadings,
alternative titles or taglines. 
If you do not want the subtitles to be included in the table of contents, just use
standard markup, for example <p> elements, as shown in the next example. Of
course, CSS rules can be applied to change colors, sizes, etc.

1. <header>

2.     <h1>HTML 5.1 Nightly</h1>

3.     <p>A vocabulary and associated APIs for HTML and XHTML</p>

4.     <p>Editor's Draft 9 May 2013</p>

5. </header>
  

Best practice #2: try not to rely on implicit sectioning,


use <section>, <article>, etc. instead of just <h1>...<h6>
The example below defines several implicit "sections" by using <Hx> directly (at lines
7 and 9):

Ok version (no explicit sections everywhere):

1. <body>

2. <h4>Apples</h4>

3. <p>Apples are fruit.</p>

4. <section>

5.      <h2>Taste</h2>

6.      <p>They taste lovely.</p>

7.      <h6>Sweet</h6>

8.      <p>Red apples are sweeter than green ones.</p>

9.      <h1>Color</h1>

10.      <p>Apples come in various colors.</p>

11. </section>
12. </body>

Better version (best practice):

1. <body>

2. <h1>Apples</h1>

3. <p>Apples are fruit.</p>

4. <section>

5.      <h2>Taste</h2>

6.      <p>They taste lovely.</p>

7.      <section>

8.          <h3>Sweet</h3>

9.          <p>Red apples are sweeter than green ones.</p>

10.      </section>

11. </section>

12. <section>

13.      <h2>Color</h2>

14.      <p>Apples come in various colors.</p>

15. </section>

16. </body>

Both of the examples above are semantically identical and produce the same outline:
Knowledge check 1.3.6 (not graded)
0 points possible (ungraded)

1. <section>

2. <header>

3. <p class = "article title" > Blog post of April 2020 </p>

4. <p> Posted by Michel Buffa... </p>

5. </header>

6. ...

7. </section>
___________________________________________________________________
__________

Does this example follow the best practices presented in this section of the course?

Yes

No
non répondu
Here we propose a small piece of JavaScript code you can use in your documents to
display an embedded table of contents. 

This example is a simple document, with a hyperlink that, once clicked, displays the
table of contents in an <aside> element in the main <section>. Just look at the
source code and copy/paste the link into your own HTML documents.

Online example at JsBin.

Extract of source code:

1. <body>
2. <h1>This is an example of embedded table of content</h1>
3. <section>
4.      <header>
5.          <h1>First section of the document (this is a h1)</h1>
6.          This is a subheading...
7.      </header>
8.      <h2>First subsection of the first section (a h2)</h2>
9.      <p>Blah Blah...</p>
10.  </section>
11. <section>
12.      <h1>Second section of the document (a h1)</h1>
13.      <h2>First subsection (a h2)</h2>
14. </section>
15. <aside>
16.      <h3>Table of contents</h3>
17.      <a href="javascript:(function(){...})();"
18.         title="TableDeMatiere">
19.         Click here to display the table of contents!
20.      </a>
21. </aside>
22. </body>

Best practice: visualizing the table of contents is useful for debugging the structure
of your page, and checking the presence of headings after sectioning content.

Indeed, tools that generate the table of contents are a good way to debug the
structure of your page. Is the hierarchy correct? Is it what I wanted when I designed
my page?

They are also useful for checking the presence of headings in each sectioning
content. If some headings are missing, the table of contents will display some
"untitled entries". Remember that having a heading after each sectioning content is a
good practice in terms of accessibility.

Knowledge check 1.3.7 (not graded)


0 points possible (ungraded)
1. Simple HTML5 blog
2. Blog posts for April 2020
1. Information about this example
2. History
3. HTML vs XHTML
4. Untitled SECTION
3. Tag cloud
Is this outline ideal?
No
Yes
non répondu

If you use <nav> / <header> / <footer> etc. to structure your document, you can


also use <main> to identify the main content of the document. Doing so provides a
navigable document structure for assistive technology users as well as styling hooks
for devs.

We have seen the different sectioning elements of HTML5, so why didn't we talk
about the <main> element earlier in this part of the course? Shouldn't
<main>...</main> be used in place of  <div class="main">...</div>?

The <main> element is supported by major modern browsers (see the


corresponding support table on CanIUse and MDN's brower compatibility page).

This element is subject to some constraints:

o There must not be more than one <main> element in a document,

o It must not be a descendant of an <article>,<aside>, <footer>,


<header>, or <nav> element.

And finally, here are some examples (from the HTML5 specification)  that mix
the <main> element with the other sectioning elements already seen in the course:

1. <!-- other content -->


2.
3. <main>
4.
5.    <h1>Skateboards</h1>
6.    <p>The skateboard helps kids to get around.</p>
7.
8.    <article>
9.       <h2>Longboards</h2>
10.       <p>Longboards are a type of skateboard with a longer
11. wheelbase and larger, softer wheels.</p>
12.       <p>... </p>
13.       <p>... </p>
14.    </article>
15.
16.    <article>
17.       <h2>Electric Skateboards</h2>
18.       <p>These no longer require the propelling of the skateboard by means of the feet;
rather an electric motor propels the board, fed by an electric battery.</p>
19.       <p>... </p>
20.       <p>... </p>
21.    </article>
22.
23. </main>
24.  
25. <!-- other content -->

Here is another example (also from the specification). Here the <main> element


contains a <nav> element consisting of links to subsections of the main content:

1. <!DOCTYPE html>
2.    <html lang="en">
3.       <head>
4.          <meta charset="utf-8"/>
5.          <title>Graduation Ceremony Summer 2022</title>
6.       </head>
7.       <body>
8.        <header>The Lawson Academy:
9.          <nav>
10.             <h2>Click these links to navigate...</h2>
11.             <ul>
12.                <li><a href="courses.html">Courses</a></li>
13.                <li><a href="fees.html">Fees</a></li>
14.                <li><a>Graduation</a></li>
15.             </ul>
16.          </nav>
17.       </header>
18.       <main>
19.          <h1>Graduation</h1>
20.          <nav>
21.             <h2>Please choose:</h2>
22.             <ul>
23.                <li><a href="#ceremony">Ceremony</a></li>
24.                <li><a href="#graduates">Graduates</a></li>
25.                <li><a href="#awards">Awards</a></li>
26.             </ul>
27.          </nav>
28.          <h2 id="ceremony">Ceremony</h2>
29.          <p>Opening Procession</p>
30.          <p>Speech by Valedictorian</p>
31.          <p>Speech by Class President</p>
32.          <p>Presentation of Diplomas</p>
33.          <p>Closing Speech by Headmaster</p>
34.          <h2 id="graduates">Graduates</h2>
35.          <ul>
36.             <li>Eileen Williams</li>
37.             <li>Andy Maseyk</li>
38.             <li>Blanca Sainz Garcia</li>
39.             <li>Clara Faulkner</li>
40.             <li>Gez Lemon</li>
41.             <li>Eloisa Faulkner</li>
42.          </ul>
43.          <h2 id="awards">Awards</h2>
44.             <ul>
45.                <li>Clara Faulkner</li>
46.                <li>Eloisa Faulkner</li>
47.                <li>Blanca Sainz Garcia</li>
48.             </ul>
49.          </main>
50.       <footer>Copyright 2012 B.lawson</footer>
51.    </body>
52. </html>
Best practice
For accessibility matters, a best practice is to split your page content into "regions"
defined by the five 5 elements (aside, footer, header, main and nav) learned
this week. 

We recommend this article written by Steve Faulkner: "Easy content organisation


with HTML5" (24 September 2015). Steve explains in details how to organize an
HTML document into "regions" based on the semantic markup elements we have
seen so far during Week 1 of this course.

External resources:

o This document has been written by the W3C HTML5 Working Group, which details
the different use-cases for this element

o Rationale and use cases for standardizing a 'main content' HTML feature

o On MDN's Web Docs: the main element

Knowledge check 1.3.8 (not graded)


0 points possible (ungraded)

1. <!-- other content -->


2. <article>
3. <main role = "main" >
4. <h2> Longboards </h2>
5. <p> Longboards are a type of skateboard with a longer
6. wheelbase and larger, softer wheels. </p>
7. </main>
8. </article>
9. <!-- other content -->
___________________________________________________________________
__________

Is this code correct?


No
Yes
Let's go back to our blog example and see what can be improved:

o Do we have a heading after each sectioning element?

o Did we use sectioning elements or implicit sections?

o Can we embed a table of contents?

The blog example is online at JsBin:  let's see below what the Google Chrome
HTML5 Outliner extension showed.
Also note that in this example, we used H1s after each sectioning element, and we
still get a hierarchy, some H1s are inside an <article> that is in a <section> (this
corresponds to the third example given in the "heading and sectioning elements" part
of the course):

1. <section>
2.    <header>
3.      <h1>Blog posts for April 2012</h1>
4.    </header>
5.    <article>
6.      <header>
7.        <h1><a href="">Information about this example</a></h1>
8.        This example is a modified version
of <a href="https://example.com/blog/index.html">https://example.com/blog/index.html</a>
9.      </header>
10.      ...
11.    </article>
12. </section>

With this technique, parts of the document can be moved more easily, or integrated
inside an RSS stream, without the need to renumber the headings.

Beware that this technique will require you to use some CSS styling, and may
confuse some screen readers that do not yet take into account this way of computing
the heading hierarchy. A simple fix is to use an H1 right after the <body> and use
only H2...H6 inside <section>, <article>, <nav> and <aside>.

Let's fix the missing heading


We need to add a heading in the <nav> element. This will both fix the outline of the
document by removing the untitled entry, and will also make screen readers happy
as they will better vocalize the structure of the page (it will say "entering nav" followed
by the vocalization of the heading content).

1. <nav>
2.    <header>
3.      <h1>Navigation menu</h1>
4.    </header>
5.    <ul>
6.      <li><span>Blog</span></li>
7.      <li><a href="">About</a></li>
8.      <li><a href="">Contact</a></li>
9.    </ul>
10. </nav>

Here is the fixed result:


A common remark from Web designers is: "we do not want a heading content
displayed systematically after a <nav>, or an <aside> element..."

BEST PRACTICE #1: In order to NOT display the heading content on screen


the recommended technique  is described in this article by Steve Faulkner. Do
not use display:none or visibility:hidden in your CSS stylesheet, as
in that case the heading content will never be vocalized by screen readers, and
more generally by assistive technologies. 

As an illustration of the recommended technique, see this JSBin version of the


blog example that hides the <h2>Navigation menu</h2> from
the <nav>...</nav> element, using the CSS technique explained in the
above link.

BEST PRACTICE #2: it is not advised to include interactive content (links,


controls etc) that is hidden offscreen (it is in fact a violation of the W3C WCAG
2.0 Guidelines). All interactive content must have a visible focus indicator (and
be on screen when focused).
Embedding a table of contents and adding a <main> element
In the previous section, we saw how to embed a table of contents using some
JavaScript code borrowed from the Google Chrome HTML5 outliner extension.

Let's add this piece of code (we removed the JS details from this extract):

1. <aside>
2.    <h1>
3.      <a href="javascript:(function(){...});"
4.         title="TableOfContents">
5.         Click here to display the table of contents!
6.      </a>
7.    </h1>
8. </aside>

We also added a <main> element to identify the main content of the page composed
of the big section with all blog posts:

1. <main>
2.   <section>
3.      <header>
4.          <h2>Blog posts for April 2012</h2>
5.      </header>
6.      ...
7. </main>
Use H1 as top level headings only, use H2...H6 in sectioning
content
As explained in the article HTML5 Document Outline and in the W3C HTML Wiki , it
is risky to use nested H1s, as browsers do not correctly implement the "outline
algorithm".

The blog example uses nested H1’s. If you check it with the W3C conformance
checker, it issues a warning: "Consider using the h1 element as a top-level heading only
(all h1 elements are treated as top-level headings by many screen readers and other tools)."

So, while this is just a warning, we do prefer to use H1s only as top level elements,
and replace the H1s we had after <section>, <article>,
<nav> and <aside> elements respectively by a H2s and H3s. 

Extract from source code:

1. <nav>
2.    <header>
3.      <h2>Navigation menu</h2>
4.    </header>
5.    ...
6. </nav>
Finally, the fixed example

 Check it online with this JsBin

Knowledge check 1.3.9 (not graded)


0 points possible (ungraded)
I have a heading after a  <nav > or an  <aside > element. What is to be done if I do not
want it to appear on the page?
Prefer not to use a heading in  <nav > or  <aside > elements.
Hide it using the CSS  <display:none > rule.
Use CSS, as this is a best practice described in an article (by Steve Faulkner) we
refer to in this course.
Hide it using the CSS  <visibility:hidden > rule.
In this section, we show some "classic" CSS layout techniques for designing an
HTML page that uses the new sectioning elements. 

We embed examples from this very good post about "Positioning content". This is a
recommended reading as it details how to use the CSS float property to layout a
Web page.
The 4 examples below are given "as is" to give you some hints. There are lots of
other possibilities on using CSS to position element.

Example #1: a <section> on the left and an <aside> on the


right, using the float and width CSS properties
This example uses the following HTML structure (notice that we use the "HTML entity
syntax" for displaying "<" or ">". For example, &lt; displays a "<" character).

1. <header>

2. <code>&lt;header&gt;</code>

3. </header>

4.  

5. <section>

6. <code>&lt;section&gt; <br> float: left;</code>

7. </section>

8.  

9. <aside>

10. <code>&lt;aside&gt; <br> float: right;</code>

11. </aside>

12.  

13. <footer>

14. <code>&lt;footer&gt;</code>

15. </footer>

Here we use the CSS rule float:left for the <section> and the CSS


rule float:right for the <aside>. When an element floats, it goes out of the normal
flow of the HTML element. Then by default it floats to the edge of its parent; and its size
depends on the elements it contains. So, in order to fill the whole horizontal space, we prefer
here to "force the width" by setting the CSS width property with a percentage.  So we
took width: 63% for the <section> on the left and width:30% for the <aside> on
the right.
You can look at the complete CSS code in the interactive example below (click on
the CSS or HTML text in the menu bar below, or click "edit on codepen" to change
the code and see the results):

Example from the live coding video, a slight adaptation of the technique described above
Also available online at JSBin.

Example #2: three sections centered, of equal size, also using


the float and width CSS properties
Here we show how to make a 3 column layout using the CSS float property.

HTML code:

1. <header>

2. <code>&lt;header&gt;</code>

3. </header>

4.  

5. <section>

6. <code>&lt;section&gt; <br> float: left;</code>

7. </section>

8.  

9. <section>

10. <code>&lt;section&gt; <br> float: left;</code>

11. </section>

12.  

13. <section>

14. <code>&lt;section&gt; <br> float: left;</code>

15. </section>

16.  
17. <footer>

18. <code>&lt;footer&gt;</code>

19. </footer>

Instead of having one element with a float:left and one element with


a float:right property, we instead use float:left for all three of them, and we
give a  width:30% CSS property value to each <section>. We also set a
small margin so that the colums have a gap between them.

Look at the CSS code in the example below:

Example #3: same result using the CSS flex property


This example uses the CSS flex property to achieve a result similar to the one
shown in Example 2.
There are many articles on Flexbox and we recommend those from Rachel Andrew
on Smashing Magazine: "Use cases for Flexbox", "Flexbox: how big is that flexible
box", etc.

Example #4: another example written by a student, that uses the


flex property
This example also uses all the structuring elements we saw: main, article, section,
etc. It uses only the simplest parts of the FlexBox CSS module, so it should be easy
to understand, even for CSS beginners:

External resources

 An article on CSS Tricks: All about floats

 Old but good article on "A List Apart" (ALA): CSS Floats 101

 Another article on Lifewire: Understanding CSS float

 On MDN's Web Docs: the float CSS property and the clear CSS property

These elements have been introduced for displaying a foldable zone in an HTML
document.

In the screenshot below, taken from the W3C specification page, the text next to the
horizontal arrow is a <summary> element, and the text displayed when we click on
the summary part, is the <details> element. This is a sort of "accordion" with
foldable content.
The <details> element generates a simple widget to show/hide element contents,
optionally by clicking on its child <summary> element.

Here is an example of what can be done using these elements ) see the online
version on JSBin:
And here is what is displayed after clicking on the small arrow-shaped icon to the left
of the summary:

Here is the code of this example:

1. <!DOCTYPE html>
2. <html lang="en"> ...

3. <body>
4. <details>
5. <summary>
6. How to beat the boss...spoiler alert !
7. </summary>
8. <p> Just aim to the red spots near his eyes</p>
9. <p>Keep shooting at these spots until the eyes open, then hit quickly both eyes with your
laser beam.</p>
10. </details>
11. </body>
12. </html>

The <summary>...</summary> is inside a <details>...</details> element.


By clicking on the icon at the left of the summary, the content of
the <details> value is displayed/hidden.

<details> blocks can be embedded inside one another, like in this example:


Step 1: all folded:

Step 2: click on top level summary icon, the first "hidden" part appears...

Step3: click on embedded summary icon inside the part that has been previously
unfolded

Source code of this example, see the summary/details inside another one:

1. <details>
2. <summary>
3. How to beat the boss...spoiler alert !
4. </summary>
5. <p> Just aim to the red spots near his eyes</p>
6. <p>Keep shooting at these spots until the eyes open, then hit quickly both eyes with your
laser beam.</p>
7. <details>
8. <summary>
9. Bonus and spoiler No 2: get a new weapon by cutting the tail of the boss.
10. </summary>
11. <p>Before finishing him, try to cut his trail, you will get a new weapon</p>
12. <p>Just try to stay behind him as long as you can, hitting his tail with your
melee weapon, after a few hits the trail will fall and you will get a new bonus weapon,
then finish the boss.</p>
13. </details>
14. </details>
CSS pseudo classes for styling summary icons
There are CSS pseudo classes to style this icon when it is in the open or closed state.
Support for these is still incomplete as of June 2020 (works on Google Chrome, Opera, Safari,
not in FF).

Example1 (see online example):

The color and background of the icon on the left are specified by the following CSS
rule, which uses the pseudo class ::-webkit-details-marker

In this example: red arrow, white background.

1. summary::-webkit-details-marker {
2. color:#FF0000;
3. background:#FFFFFF;
4. }
Once opened, the selector details[open] can style the icon when <details> is
unfolded. In this example: blue arrow, turquoise background. Here is the
corresponding CSS rule:

1. details[open] summary::-webkit-details-marker {
2. color:#0000FF;
3. background:#00FFFF;
4. }

It is also possible to change the icon itself using the CSS pseudo class :after

Example 2 (see it online):

CSS rules used in this example:

Use a "+" shaped icon, pink, bold, etc... :

1. summary:after {
2. content: "+";
3. color: #FF00FF;
4. float: left;
5. font-size: 1.5em;
6. font-weight: bold;
7. margin: -5px 5px 0 0;
8. padding: 0;
9. text-align: center;
10. width: 20px;
11. }

Use a "-" shaped icon, white, when details are displayed:

1. details[open] summary:after {
2. content: "-";
3. color: #FFFFFF
4. }
Current browser support

 On CanIUse: compatibility table for details and summary elements

Knowledge check 1.4.1 (not graded)


0 points possible (ungraded)
Select the good way to define the widget:

1. <summary>
2. <details>
3. How to beat the boss
4. </detaill>
5. </summary>

1. <summary>
2. How to beat the boss
3. </summary>
4. <details>
5. <p> Just aim to the red spots near his eyes </p>
6. </details>

1. <details>
2. <summary>
3. How to beat the boss
4. </summary>
5. <p> Just aim to the red spots near his eyes </p>
6. </details>
non répondu
The <time> element
The <time> element is useful for marking a time or a duration in a document.

It provides both a human readable part (the part between <time> and </time>)


and a machine readable part contained within a datetime attribute. Dates are
expressed as YYYY-MM-DD.
The machine readable part adds semantics that can be used by search engines for
indexing, by browsers or by browser extensions, or by JavaScript code. Useful
scenarios include generating alerts for birthdays, automatically adding dates or
events that contain <time> elements in a calendar, etc.

Example:

1. We open at <time>10:00</time> every morning.

2.

3. I have a meeting the <time datetime="2020-02-14">Monday 14/02/2020.</time>.

4. Blog posts from the year <time datetime="2020">2020</time>.

5. Archives, blog posts for <time datetime="2020-04">April 2020</time>

6. This recipe was published by Michel the <time datetime="2020-04-


16">April 16, 2020</time>.
The datetime attribute
The datetime attribute can be used for indicating a date/time or a duration.

Date/time values

Supports different specifications of time such as "a year", "a month in a year", "a
week in a year", "a time", etc... 

Here are some examples:

Different syntaxes of the datetime attribute

datetime attribute values Interpretation

<time datetime="2020"> The year 2020

<time datetime="2020-11"> November 2020


<time datetime="11-13">  November 13th (any year)

<time datetime="2020-W21"> Week 21 from year 2020

<time datetime="2020-11-13
09:00"> November 13th year 2020, time = 9:00

Same as previous example, both syntaxes are supported, with and


<time datetime="2020-11- without the "T" between date and time.
13T09:00">

<time datetime="09:00Z"> 9:00 in the morning, GMT

<time datetime="09:00-05"> 9:00 in the morning, GMT minus 5 hours

9:00 in the morning, GMT plus 5 hours 45 minutes, (for example,


<time datetime="09:00+05:45"> Nepal is 5:45 ahead of  GMT)

Duration values
Duration values use the prefix “P” for “period” as in <time
datetime="P4D"> (period = four days)...
So you start the attribute string value with a "P", followed by a duration value that
ends with another letter indicating the unit used: "D" for "days",  “H” for hours, “M” for
minutes and “S” for seconds. 

You can separate the different elements "P", value and unit with spaces, but this is
optional. So <time datetime="P4D"> is a duration of 4 days, as is <time
datetime="P 4 D">.

Using a “T” after the “P” marker allows you to indicate a more accurate duration
time: <time datetime="PT4H 6M 12.55S"> is a duration of 4 hours, 6 minutes
and 12.55 seconds.

Alternatively, you could use also a duration time component.

From Bruce Lawson's article : "Whichever you choose, it’s represented internally as
a number of seconds. Because of this, you can’t specify a duration in terms of
months, because a month isn’t a precise number of seconds; a month can last from
28 to 31 days. Similarly, a year isn’t a precise number of seconds; it’s 12 months and
February sometimes has an extra day.

You still can’t represent dates before the Christian era, as years can’t be negative.
Neither can you indicate date ranges. To mark up From “21/02/2012 to 25/02/2012″,
use two separate <time> elements."

Examples:

1. <h2>Recipe:</h2>

2. <ul>

3.   <li> Preparation time: <time datetime="PT30M">30 minutes</time> </li>

4.   <li> Cooking time:     <time datetime="PT10M">10 minutes</time> </li>


5. </ul>
The <time> element with no attributes

Used without attributes, the value between the opening <time> and


closing </time> should follow the syntax given by the specification so that machines
can understand it (same syntax as the one presented for the datetime attribute in
the previous section). However it is recommended to use a datetime attribute, as it
gives more freedom in the way you can display the date/time/duration in a human-
readable form. 

External resources:

o From the specification: https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-


time-element

o On MDN's Web Docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time

 MDN's browser compatibility table for <time>

o Old but interesting article by Bruce Lawson: https://www.brucelawson.co.uk/2012/best-of-


time/

o A CSS Tricks' article: "The 'time' element

The <mark> element

The HTML <mark> tag is used for indicating text as marked or highlighted for


reference purposes, due to its relevance in another context.

Some use cases:

o Display search results with search strings highlighted in the results.

o >Highlight important parts of a text, such as "quoting parts", etc.

o Replace <strong> and <em> with <mark> when suitable.

Example 1: https://jsbin.com/tafelic/edit?html,output

Source code:

1. <!DOCTYPE html>
2. <html lang="en">

3. <head>

4. <meta charset=utf-8 />

5. <title>JS Bin</title>

6. </head>

7. <body>

8. <p>Project is due in <mark>.zip format</mark> next monday.</p>

9. </body>

10. </html>

Example 2:

Source code:

1. <body>

2. <pre>

3. <code><mark>var</mark> i = 3;</code>

4. </pre>

5. <p>The var keyword is used to declare a variable in JavaScript.</p>

6. </body>
Change the default style of the <mark> element

If you don't like the default yellow background, you may use CSS to change the style
of the <mark> element:

For example:
... comes with this CSS rule:

1. mark {

2.     background-color: green;

3.     color: yellow;

4. }
External resources:

o From the specification: https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-


mark-element

o On MDN's Web Docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark

 MDN's browser compatibility table for <time>

o An article on Web Platform News: "The <mark> element could help make your text more
scannable"

Knowledge check 1.4.3 (not graded)


0 points possible (ungraded)

When would you use the mark element?

To download a file

To highlight a text

To add a link

To make a text bigger


non répondu

The old way to download files using HTML and HTTP


Everyone knows the classic way to make hyperlinks, using <a href="...">some
text</a>. What happens when you click on the hyperlink depends on the MIME type
received by the browser. If you link to a file the browser knows how to render (an
html page, a gif, jpg, or png image, etc.) there is a good chance that the MIME type
received by the browser will be something like this:

1. Content-type: text/html, text/plain, image/gif, image/jpg, etc.

For example,  HTML code such as this:

1. <a href="toto.jpg">

1.     please right click this link to download

2.     the toto.jpg picture</a>

...will ask the remote HTTP server to send back the toto.jpg file. The browser will
receive in the response HTTP header from the server (and by default the browser will
display the image in a new tab):

1. ...

2. Content-type: image/jpg

3. ...

However, if the link points to some PHP code,  Java servlet code, or any kind of
script/application on the server side, this remote server code can send in its HTTP
response a Content-type that may force the browser to download the image
instead of rendering it.

It may also propose a name for the file to be downloaded that may be different
from the one that appears in the URL of the href attribute. This can be done by
generating, in addition to the Content-type line in the response HTTP header,
a Content-Disposition line that looks like this:

1. Content-Disposition: attachment; filename="MyImage.png";

Here are some extracts from a Java Servlet that generate a zip file and forces the
browser to propose downloading it using a specified name:

1. protected void doGet(HttpServletRequest request, HttpServletResponse response)

2. throws ServletException, IOException {

3.    try {

4.      // Build the zip file


5.        String path = getServletContext().getRealPath("data");

6.        File directory = new File(path);

7.        String[] files = directory.list();

8.        if (files != null && files.length > 0) {

9.          byte[] zip = zipFiles(directory, files);

10.          ServletOutputStream sos = response.getOutputStream();

11.

12.          // generate a HTTP response that forces the download

13.          response.setContentType("application/zip");

14.          response.setHeader("Content-Disposition",

15.                             "attachment; filename=\"DATA.ZIP\"");

16.          sos.write(zip); sos.flush();

17.        }

18.     } catch (Exception e) {

19.        e.printStackTrace();

20.     }

21. }

The above example will cause the browser that invoked this server-side code to start
the download of a file named "DATA.ZIP".

To download a file using an arbitrary name:


the download attribute
HTML5 proposes the use of a new attribute named download to download
resources rather than navigating to them. The example below shows how to trigger
the download of an image by the browser (instead of rendering it, which is the default
behavior) with a name different from the name of the resource.

1. <a href="normal.gif" download="MichelBuffa.gif">

2.     download a picture of Michel Buffa

3. </a>

This will indeed force the download of an image with a filename different from its
original filename on the server side. Here is a screen capture of the Web browser
while downloading the picture. We can see in the status bar the name of the link (the
image is "normal.gif") and the downloaded file is "MichelBuffa.gif":

WARNING: since 2015, and for security reasons, the image should be located on
the same domain as the HTML page that contains the link (using a relative URL
works well, for example, but linking a page on another domain will not work - it will
keep its original name).

Interesting applications: serverless download

Serverless download demo (by E.Bilderman)


This demo shows the use of the download attribute together with the HTML5 File,
FileSystem and FileWriter APIs (to be studied later in this course) for generating on-
the-fly content from JavaScript code, and proposing downloading it to a file.  

We won't detail this demo here, but take a look if you are curious to see what can be
done with this new download attribute. As the FileWriter and FileSystem APIs are
still supported only by Google Chrome (other browsers need polyfills), you will need
Google Chrome to try it.
We have also put the simplified source code of this demo on JSBin.com for you to
play with. See also the original demo by E. Bilderman.

External resources:

 From the specification: downloading resources

 From CanIUse: the browser support of the download attribute

The HTML5 translate attribute
HTML5 gives us a new translate attribute. This attribute is used to limit the impact
of  translation tools such as Google Translate by prohibiting the translation of certain
content. In many cases some parts of a document should not be translated.

Use cases include:

o HTML pages that contain source code: you would certainly not like to see the Java or PHP or
whatever programming language parts of your page translated into another spoken
language!
o Video game Web sites that propose cheat codes; the codes do not have to be translated,

o Street names, author names in an "about" page must not be translated,

o etc.

Both Google translate and Microsoft online translation services already offer the


ability to prevent translation of content by adding markup to your content, although
they do it in (multiple) different ways. Hopefully, the new attribute will help
significantly by providing a standard approach.

Principle: give hints to translating tools


The specification about the translate attribute tells us that  "The translate attribute
is an enumerated attribute that is used to specify whether an element's attribute
values and the values of its Text node children are to be translated when the page is
localized, or whether to leave them unchanged.

The attribute's keywords are the empty string, yes, and no. The empty string and
the yes keyword map to the yes state. The no keyword maps to the no state. In
addition, there is a third state, the inherit state, which is the missing value default
(and the invalid value default)."

Example illustrating how to specify parts of an HTML element that should not be translated:

1. <span translate="no" class="author">Michel Ham</span>

In the above example, a <span> element defines an author (of a blog, for example)
who is named Michel Ham. However, his family name is the same as pork and would
be translated to "Michel Jambon" in French, or Michel Jamón in Spanish...

Using the translate="no" attribute should prevent this behavior...

1. <span translate="no" class="author">Michel Ham</span> is a professor

2. from the University of Nice,France.

Will be correctly translated into French by:

1. "Michel Ham est un professeur de l'Université de Nice, France."

...where all of the end of the sentence has been translated except the author's name.

Inheritance between elements


When you define an element as not being translatable, its children inherit this
behavior and are themselves not translatable. The reverse is also true. 
1. <p translate="no">This is a text in a paragraph element, that should not be translated: the p
element has a translate="no" attribute.<span> This part that is in a span element embedded
within the paragraph. It does not have a translate attribute but inherits the translation-mode of
the p and will not be translated too</span>. This is the end of the paragraph...</ p>
External resources:

o From the specification: the translate attribute

o From MDN's Web


Docs: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/translate

 Its corresponding browser compatibility table

o An article from W3C's Internationalization Activity: "Using HTML's translate attribute"

Knowledge check 1.4.4 (not graded)


0 points possible (ungraded)

1. <a href = "/images/batman_robin_car_superpower_007.rar"

2. download = "Batmobile.rar" >

3. download a picture of Michel Buffa

4. </a>
___________________________________________________________________
__________

What will be the name of the downloaded file?

Batmobile.rar

batman_robin_car_superpower_007.rar
non répondu

There are 3 ways to provide machine-readable content embedded in a classical Web


document: HTML+RDFa, microformats and microdata. In this section, we focus on
microdata.

Adding microdata to Web pages helps search engines to better understand the
pages' content, their topics, etc. The main purpose of microdata is Search Engine
Optimization (SEO).

This information is not visible to humans: it is pure semantic information. Popular


kinds of microdata are events, a person's profile, the description of an organization,
the details of a recipe, a product description, a geographical location, etc. 
Quick example of microdata that describes a person

1. <section itemscope itemtype="https://schema.org/Person">

2.     <h1>Contact Information</h1>

3.     <dl>

4.       <dt>Name</dt>

5.       <dd itemprop="name">Michel Buffa</dd>

6.       <dt>Position</dt>

7.       <dd><span itemprop="jobTitle">

8.            Professor/Researcher/Scientist</span> for

9.           <span itemprop="affiliation">

10.               University of Côte d'Azur, France

11.           </span>

12.       </dd>

13.     </dl>

14.     <!-- SURFACE ADDRESS GOES HERE -->

15.     <h1>My different online public accounts</h1>

16.     <ul>

17.        <li><a href="https://www.twitter.com/micbuffa"

18.               itemprop="url">Twitter profile</a></li>

19.        <li><a href="https://www.blogger.com/micbuffa"

20.               itemprop="url">Michel Buffa's blog</a></li>

21.     </ul>

22. </section>
We can also add  another embedded data item in the middle, such as the person's
address:

1. ...

2. </dl>

3.

4. <!-- SURFACE ADDRESS GOES HERE -->

5.

6. <dd itemprop="address" itemscope

7.     itemtype="https://schema.org/PostalAddress">

8.     <span itemprop="streetAddress">10 promenade des anglais</span><br>

9.     <span itemprop="addressLocality">Nice</span>,

10.     <span itemprop="addressRegion">Alpes maritimes, France</span>

11.     <span itemprop="postalCode">06410</span><br>

12.     <span itemprop="addressCountry" itemscope

13.           itemtype="https://schema.org/Country">

14.          <span itemprop="name">France</span>

15.     </span>

16. </dd>

17.

18. <h1>My different online public accounts</h1>

19.

20. ...

In the following sections, we look more closely


at the itemprop, itemscope and itemtype attributes.
Data that can be processed, organized, structured, or presented
in a given context
Different use cases:

o The browser, or a browser extension, may interpret the last example as an address and may propose to
send it to a map application,

o A Web crawler may interpret this as an address and display it in its responses using a dedicated
presentation layout,

o Some JavaScript code in the page can access this data,

o With other types of microdata, for events, for example, the browser may pop up a calendar application,
etc.

Note: For advanced users, Microdata is very similar to microformats, which use
HTML classes, or to RDFa, which doesn’t validate in HTML4 or HTML5. Because
RDFa was considered to be too hard for authors to write, microdata is HTML5's
answer to help embed semantics into html documents.

External resources

o W3C's HTML Microdata Working Draft

o MDN's Web Docs: Microdata

o Very good Microdata paper from code{4}lib journal

o Microdata and the microdata DOM API, old article from dev.opera.com

o Chapter from Mark Pilgrim's book about microdata, very detailed introduction about semantic
metadata in general, contains full examples with explanations about how to describe a
Person, etc.

Knowledge check 1.5.1 (not graded)


0 points possible (ungraded)

What is the correct proposition to define a city?

itemtype="http://schema.org/PostalAddress" and itemprop = "postalCode"

itemtype="http://schema.org/Country" and itemprop = "name"

itemtype="http://schema.org/PostalAddress" and itemprop = "addressLocality"

itemtype="http://schema.org/Country" and itemprop = "addressRegion"

Introduction
After seeing the principle of embedding microdata in an HTML page, we now present
some structured data test tools you can use to check if your data are correct.

One of the most popular resources for testing microdata (as well as microformats and
RDFa) is this Google page about understanding how structured data works. This
page contains a link to a structured data testing tool that you can use to see how
Google recognizes the semantic data you embed in your HTML code.

Testing a real interactive example with an "about page" for


Michel Buffa
Let's have a look now at a (small) example of an about page. It renders as a very
simple paragraph that explains who Michel Buffa is... But we embedded Microdata,
so it's interesting to see how a search engine sees it, and how it may produce
"augmented search results".

Online example at JsBin

Source code:

1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4. <meta charset=utf-8 />

5. <title>Michel Buffa</title>

6. </head>

7. <body>

8. <div itemscope itemtype="https://schema.org/Person">
9.     My name is <span itemprop="name">Michel Buffa</span>,

10.     And I'm a <span itemprop="jobTitle">professor/researcher</span> at

11.      <a href="https://www.i3s.unice.fr/" itemprop="affiliation">I3S

12.     Laboratory</a> in the south of France, near the city of Nice. My

13.     email

14.     is : <span itemprop="email">[email protected]</span>.

15.     I live in the city of

16.     <span itemprop="address" itemscope

17.         itemtype="https://schema.org/PostalAddress">

18.          <span itemprop="addressLocality">Biot</span>, in a region named

19.          <span itemprop="addressRegion">Alpes Maritimes</span>

20.     </span>

21. </div>

22. </body>

23. </html>

Rendering of the page in a browser:

Here is what Google sees of the page. We just entered its URL in the Google page
about rich snippets and structured data:
Note that the address is a fully featured embedded object in the Person's description.

Live Microdata
The Live Microdata Web site  is a bit similar to the previous one except that it shows
the extracted metadata as JSON objects: 
And the JSON view of the microdata:
Basic steps
Adding microdata to an HTML page is a really simple task and requires only
three attributes: itemscope, itemtype  and itemprop.

1 - Define a container element by adding an itemscope attribute

First, you need to add an itemscope attribute to an HTML element. This will define
the "global object" for which we will define properties. This element can be of different
types that we will describe later, but for now let us keep looking at the same example
we used in previous sections:

1. <section itemscope itemtype="https://schema.org/Person">

2. ...

3. </section>

We will look at the itemtype attribute later. Now that we have defined a global


wrapper object/element (a Person in this case), we can  add properties inside this
element to define the first name, last name, etc.
2 - Specify the vocabulary used for your microdata with the itemtype attribute of the
container element
HTML5 proposes semantic elements for representing sections, articles, headers, etc,
but it does not propose any specific elements or attributes to describe an address, a
product, a person, etc.

We need a special vocabulary to represent a person or a physical address. With


microdata you can define your own vocabulary or better, reuse one of the existing
popular vocabularies, such as schema.org. 

Microdata works with properties defined as name/value pairs. The names are defined
in the corresponding vocabulary. For example, the vocabulary for representing
a Person defines a set of property names.

As you can see in this small extract from the vocabulary (also called a "schema"), a
Person can have a name (some text), an Address (the type is defined by another
vocabulary named PostalAddress), an affiliation (defined by another vocabulary
named Organization) and so on.

We notice that one property, such as the address of a Person, may use another
vocabulary. Yes, a vocabulary may link to another vocabulary! There is also
inheritance between vocabularies! The above screenshot shows that the Person
vocabulary inherits from a Thing vocabulary, and the five first properties of the table
come from this vocabulary that describes things.

If you are a developer and if you are familiar with object oriented programming, think
of properties as class attributes and think of vocabularies as classes.

Vocabularies are meant to be shared

If one of the existing vocabularies available at the schema.org Web site fits your
needs, you should reuse it, as the most popular vocabularies are becoming de facto
standards and will be taken into account by Web crawlers, browsers, and browser
extensions.

However, if you do not find a vocabulary corresponding to your needs, keep in mind
that anyone can define a microdata vocabulary and start embedding custom
properties in their own Web pages. You need to define a namespace and put a
description of your vocabulary in a Web page that has the name of your vocabulary.

3 - Add properties using the itemprop attribute in HTML elements inside the container

Basics:

Now that you have defined a container element, you may add properties to the HTML
inside:

1. <section itemscope itemtype="https://schema.org/Person">

2.      <h1>Contact Information</h1>

3.      <dl>

4.          <dt>Name</dt>

5.          <dd itemprop="name">Michel Buffa</dd>

6.          <dt>Position</dt>

7.          <dd><span itemprop="jobTitle">

8.                Professor/Researcher/Scientist

9.              </span> for

10.              <span itemprop="affiliation">University of Nice,

11.                     France

12.              </span>

13.           </dd>

14.      </dl>

15.      <h1>My different online public accounts</h1>

16.      <ul>

17.          <li><a href="https://www.twitter.com/micbuffa"

18.              itemprop="url">Twitter profile</a></li>


19.          <li><a href="https://www.blogger.com/micbuffa"

20.              itemprop="url">Michel Buffa's blog</a></li>

21.      </ul>

22. </section>

In this example, the container is a <section> that corresponds to a Person (we


have one clue here: the name of the vocabulary given by the itemtype attribute),
and each property defined inside this section is identified by the value of
the itemprop attribute of sub-elements.

The line: 

1. <dd itemprop="name">Michel Buffa</dd>

...defines a property called "name" that has a value of "Michel Buffa" (the text value
between the opening and closing tags of the <dd> element).

Nesting microdata items

As we saw with the Person/Address example at the beginning of this chapter, it is


possible to nest microdata items inside one another.

Give an element inside a microdata container its own itemscope attribute with the


recommended itemtype attribute for indicating the name of the vocabulary used by
the nested microdata.

Again, look at the Person/Address example:

1. ...

2. </dl>

3.

4. <!-- SURFACE ADDRESS GOES HERE -->

5.

6. <dd itemprop="address" itemscope

7.     itemtype="https://schema.org/PostalAddress">
8.      <span itemprop="streetAddress">10 promenade des anglais</span><br>

9.      <span itemprop="addressLocality">Nice</span>,

10.      <span itemprop="addressRegion">Alpes maritimes, France</span>

11.      <span itemprop="postalCode">06410</span><br>

12.      <span itemprop="addressCountry" itemscope

13.            itemtype="https://schema.org/Country">

14.           <span itemprop="name">France</span>

15.      </span>

16. </dd>

17.

18. <h1>My different online public accounts</h1>

19.

20. ...

The properties at lines 8-12 refer to the address nested microdata (they are defined
in the Address vocabulary, not the Person vocabulary), and "France" (line 14) is a
property that refers to the Country vocabulary.

Several properties with the same name but different values

It is possible to use the same property name several times in one microdata object,
but with different values:

1. ...

2. <h1>My different online public accounts</h1>

3. <ul>

4. <li><a href="https://www.twitter.com/micbuffa" itemprop="url">Twitter

5.       profile</a></li>
6. <li><a href="https://www.blogger.com/micbuffa" itemprop="url">Michel

7.       Buffa's blog</a></li>

8. </ul>

This defines the fact that Michel Buffa has two online accounts, and the two
properties have the name url, each with its own value.

It is possible to set more than one property at once, with the same value

Here are some microdata that represent a song. In this example, at line 5 we set  two
different properties: genre and keywords with the same value (see
the MusicRecording schema definition):

1. <div itemscope itemtype="https://schema.org/MusicRecording">

2. <h2>The song I just published</h2>

3. <ul>

4. <li>Name: <span itemprop="name">Please buy me on itunes, I need money!</span></li>

5. <li>Band: <span itemprop="genre keywords">Punk, Ska</span></li>

6. </ul>

7. </div>

And so on...

Now, let's see what elements are compatible with the itemprop attribute and where
the values of the properties are located, depending on each element type.

The HTML elements compatible with the itemprop attribute

If the itemprop attribute appears on a:

Elements that can be associated with microdata

HTML5 elements microdata value associate


<a> ,  <area> ,  <audio> ,  <embed> ,  <iframe> , 
The data is the url in the element's  href ,  src , or  data  attribute, as
<img> ,  <link> ,  <object> ,  <source> ,
or  <video>  element inside a container of personal contact information can be rec
downloaded accordingly.
element

The data is the time in the element's  datetime  attribute. This lets yo
<time>  element your text content but still indicate exact date and time.

The data is whatever appears in the content attribute of the  <meta>  e


<meta>  element include some data that isn't actually in the text of your page.

anything else The data is whatever is in the text of the element.

For example, the value of a property defined in an <img> element will be the value of
the src attribute:

1. <img itemprop="image" src="MichelBuffa.png" alt="A great professor">

Or for a <time>, it will be the value of the datetime attribute:

1. <time itemprop="birthday" datetime="1965-04-16">April 16, 1965</time>

Or for an <a> element, the value will be the value of the href attribute:

1. <a href="https://www.twitter.com/micbuffa" itemprop="url">profile</a>
Knowledge check 1.5.3 (not graded)
0 points possible (ungraded)

What is the correct schema from schema.org for describing a person's address?

https://schema.org/LocalAddress

https://schema.org/PostalAddress

https://schema.org/SurfaceAddress

https://schema.org/Address
There are many tools available (most are free) that you can use for generating,
visualizing and debugging microdata. We list some of them in this page, but feel free
to share the tools you find / like in the forums.

Microdata generators
To automatically generate microdata for describing persons, restaurants, movies, products,
organizations, etc., there is a wide variety of microdata generators such as these listed below
(but do not hesitate to search for "microdata generators" using your favorite search engine,
and you will find lots!):

o The Ultimate Microdata Generator

o The MicroData Generator

o The Schema Markup Generator (JSON-LD)

Example:

Here, we propose a few links to Web pages that were created by students of
previous editions of this course).
The students had to create a Web page to introduce themselves, with some
information including: name, job, employer, location, etc., and of course enrich the
page with microdata. They also had to follow the best practices concerning the new
structural elements, headings, etc.

Click on these pages and look at the source code...

Example #1
Visit the exemple #1 online.

Structure:

Microdata:
Example #2
View the example #2 online.

The <video> element of HTML5 is one of the two "Flash killers" (the other being
the <canvas> element). It was designed to replace horrible things like
embedded Flash objects that used to be around.

Before HTML5, how did we embed videos in a Web page?


Like this!

1. <object width="425" height="344">

2.    <param name="movie"

3.           value="https://www.youtube.com/v/9sEI1AUFJKw&hl=en_GB&fs=1&">

4.    </param>

5.    <param name="allowFullScreen"   value="true"></param>

6.    <param name="allowscriptaccess" value="always"></param>

7.

8.    <embed src="https://www.youtube.com/v/9sEI1AUFJKw&hl=en_GB&fs=1&"

9.           type="application/x-shockwave-flash"

10.           allowscriptaccess="always" allowfullscreen="true"

11.           width="425" height="344">

12.    </embed>

13. </object>

Indeed, this was the only way to embed a YouTube video (fortunately, YouTube has
changed that now). Furthermore, embedding a Flash player made it impossible to
watch videos on some mobile platforms (especially Apple devices).

With HTML5:
The new way of doing things is a lot better... (please open this live example at JS
Bin).

The source code of this example shows the typical usage of the <video> element:

1. <video width="320" height="240" controls="controls">

2.    <source src="movie.mp4" type="video/mp4" />

3.    <source src="movie.ogg" type="video/ogg" />
4.    Your browser does not support the <video> element.

5. </video>

Please note that:

o The controls attribute indicates that a control panel with play/stop/volume/progress


widgets should be displayed;

o Usually the browser  will use the first format it recognizes  (in this case, the browser checks
whether mp4 is supported, and if not, it will check for the ogg format, and so on). Some
browsers may use a different heuristic and choose a "preferred" format.

o The <video> element is a DOM member, so  CSS styling can be applied, as well as


manipulation using the DOM API.

You will learn more about the different attributes of the <video> element later on in


the course...

Current browser support for the <video> element


The <video> element is supported by all major browsers. To get an updated
version,  see the related support table from CanIUse.

Restriction: you cannot embed a YouTube or DailyMotion video


using the <video> element
Help! <video src="my youtube video URL"></video> does not work! 

BEWARE: you cannot directly embed videos from most of the popular social Web
sites such as YouTube, Dailymotion, Vimeo, etc. For commercial reasons, and
because advertising is automatically  added to the videos, these Web sites do not
allow "regular" embedding of their videos.

While they use HTML5 to render their videos, these hosting sites (YouTube, etc.) use
rather complex techniques in order to prevent you from using them with
the <video>element. Instead, you often need to embed an <iframe> that will
render the HTML5 videos in your Web site, and of course, the advertising that comes
along with them.

Usually you have an "embed" button close to the videos that prompts you with some
HTML code that you can copy and paste for embedding.

An example using YouTube:


Here is the HTML code you need to copy and paste in order to embed a video (in this
case, a tutorial that tells you how to embed a YouTube video):

1. <iframe width="560" height="315" src="https://www.youtube.com/watch?v=9NTrwrfI-X4" f
rameborder="0" allowfullscreen></iframe>

The YouTube video embedded in this page by the above code: it's HTML5 but it's not
a <video> element directly inserted in the HTML of this page, it's an <iframe>:

External resources

o From W3C's specification: The video element

o MDN's Web Docs:  <video>: The Video Embed element

o From Apple's developer site: Safari HTML5 audio and video guide.

o Article from HTML5 Rocks: HTML5 video

o HTML5 Video Player: How to Embed a Video in HTML

Knowledge check 2.2.1 (not graded)


0 points possible (ungraded)

The video element is like any other HTML element: I can style it using CSS and interact
programmatically with it using the JavaScript DOM API.

True

False

HTML5 audio is composed of several layers:

o The <audio> element is useful for embedding an audio player into a Web page. It is dedicated
for streamed audio. It is very similar to the <video> element, both in its use and in its API.

o The Web Audio API is designed for musical applications and for adding sound effects to games. This
pure JavaScript API supports manipulation of sound samples (loops, etc.), music synthesis and
sound generation (oscillators, etc.). It also comes with a set of predefined sound processing modules
(reverb, delay, etc.).

This course will focus on the <audio> element. We present the Web Audio API and other


advanced HTML5 features in the W3Cx HTML5 Apps and Games course.

The attributes, event set and JavaScript API  of the <audio> element are just a
"reduced" version of the ones from the <video> element, and here we will only
address the differences and peculiarities.
The <audio> element, basic usage
Here is a simple example (also available online example from JSBin):

Press play to stream the neigh of a horse:   

As you can see, the code is very similar to the basic <video> element usage.

1. <!DOCTYPE html>

2. <html lang="en">

3.    <head>

4.       <meta charset="utf-8"/>

5.       <title>horse song</title>

6.

7.    </head>

8.    <body>

9.       <audio controls="controls">

10.          <source src="https://mainline.i3s.unice.fr/mooc/horse.ogg" type="audio/ogg" />

11.          <source src="https://mainline.i3s.unice.fr/mooc/horse.mp3" type="audio/mp3" /
>

12.             Your browser does not support the audio element.

13.             Download the audio/video in

14.          <a href="https://mainline.i3s.unice.fr/mooc/horse.ogg">OGG</a>

15.          or <a href="https://mainline.i3s.unice.fr/mooc/horse.mp3">MP3</a>

16.          format.

17.       </audio>

18.
19.    </body>

20. </html>

In this example, just as for the <video> element, we used the controls attribute in


order to render the play/stop, time, volume and progress widgets.

Notice the other similarities: between the <audio>...</audio> tags, we added a


text message that is displayed if the Web browser doesn't support
the <audio> element, and we used several <source>...</source> elements
that link to different audio formats for the same file. The browser will use the first
format it recognizes.

External resources

 From W3C's specification: The audio element

 From MDN's Web Docs: <audio>: The Embed Audio element

Knowledge check 2.2.2 (not graded)


0 points possible (ungraded)

HTML5 comes with several ways of handling audio - what are they?
2 correct answers.

HTML5 can use flash players

The WebAudio API

The  <music>  element

The  <audio>  element

The JavaScript sound.js library


non répondu

Most useful attributes of the <video> element

Here are the most common attributes you can use with the <video> element. They
are self explanatory...

 src: source of the video.


 width and height: size of the video. If unspecified, the default width and height of the
video will be used. If you specify one dimension but not the other, the browser will adjust the
size of the unspecified dimension to preserve the aspect ratio of the video.

 controls: If this boolean attribute is present, the browser displays its own controls for video
playback and volume.

 poster: This attribute allows you to specify an image that the browser will use while video is
being downloaded, or until the user starts playing the video. If this attribute is not specified,
the first frame of the video will be used instead.

 autoplay: This attribute asks the browser to start playing the video automatically as soon
as the page is ready.

 preload:  The preload attribute is used when autoplay is not used. It tells the browser


what to do before a user plays a video. This attribute is a hint - the browser may ignore it.
While autoplay and preload are mutually exclusive, if both are present, then preload is
ignored. Possible values:

o none: do nothing. This saves bandwidth, no video will be downloaded in background before a user or
a call to the play() method starts playing the video.

o metadata: download metadata, such as length of the video or its format.

o auto (default value): the browser will decide. This will depend on the implementation, and on the
kind of connection: wifi, 3G, data roaming etc.

 loop: Another boolean attribute that indicates to play the video in loop mode (and it starts again
when finished).

Be careful if you target mobile applications or if you have multiple videos on the same page
The autoplay attribute is not recommended if your Web site targets mobile
applications, as it may consume bandwidth even if the user is not interested in
watching the proposed video. If you target mobile devices, we recommend
using preload=none as well, as the default value for this attribute is auto.

Best practice: do not use autoplay and add preload="none" if you target


mobile devices or if you have multiple audio/video on the same page.  For
example, this page contains many audio elements and it does not make sense to
have them preload or autoplay.
About the poster attribute

If the poster attribute is missing, usually the first non-blank frame of the video will
be used as the image that is shown when the video is not playing. 

About the autoplay attribute for general use

Do not abuse of the autoplay attribute. We talked earlier about mobile applications,


but even on desktop applications it's usually a bad idea to use it (except for
WebCams and for some animations with small video loops, without sound, or for
sites like YouTube, with just videos). This is the testimony of a user in this course forum:
"When I'm following the news, I open several headlines in separate tabs. And then all
of them start screaming at me with some autoplays. I know this is supposed to make
me watch the video, but for me - it makes me close the loud tab and try another
source."

Best practice: think twice before using the autoplay attribute, even for desktop
applications.

Attributes of the <audio> element
The attributes you can use with the <audio> element are a subset of those available
for the <video> element. Except for the poster attribute, they are all recognized
and have the expected meanings: 

o src: source of an audio stream.

o controls: if this attribute is present, the browser displays its own controls for audio
playback and volume.

o autoplay: tells the browser to start playing the audio stream automatically as soon as the page is
ready - please read details in the above table.

o preload: tells the browser what to do before a user plays a sound - please read details
in the above table.

o loop:  indicates to play the audio stream in loop mode (start again when finished).

As with the <video> element, the same best practice in regard


to preload and autoplay attributes should be followed.

Knowledge check 2.2.3 (not graded)


0 points possible (ungraded)

Which of the following statements about the  preload  attribute is correct?


When present, it tells the browser to load multiple multimedia files in advance.

If this attribute is present, the browser checks if the multimedia content can be loaded
from its cache.

This attribute can take different values that will avoid preloading mutimedia content, or
on the contrary, that will tell the browser to preload this content, or tell the browser to preload
only some multimedia content metadata.

If this attribute is present in an audio or video element, the multimedia content is


preloaded as soon as the page is loaded.

The <video> and <audio> elements are just like other HTML elements, so CSS


can be used for styling, including CSS transitions, animations and transforms (this
was not possible with Flash technology).

An example of an audio player with some style


You can try this example online at JSBin.

To add some styling to the basic example we saw when we introduced


the <audio> element, we just add a <figure> with two children: an <img> and
a <figcaption>. Inside the <figcaption> we add the <audio> element from
the previous example.

MOVE THE MOUSE POINTER OVER THIS PLAYER'S ELEMENTS!

Press Play to hear the horse ! 


 

HTML source code:

1. <figure id="figaudio1">

2.   <img id="imghorse" width="200"

3.      src="https://upload.wikimedia.org/wikipedia/commons/d/d4/Nokota_Horses.jpg"

4.      alt = "a horse"/>
5.   <figcaption id="figcptionaudio1"> Press Play to hear the horse!

6.     <audio controls="controls">

7.        <source src="https://mainline.i3s.unice.fr/mooc/horse.ogg"

8.                type="audio/ogg" />

9.        <source src="https://mainline.i3s.unice.fr/mooc/horse.mp3"

10.                type="audio/mp3" />

11.        Your browser does not support the audio element.

12.        Download the audio/video in

13.        <a href=”https://mainline.i3s.unice.fr/mooc/horse.ogg”>OGG</a>

14.      or <a href=”https://mainline.i3s.unice.fr/mooc/horse.mp3”>MP3</a>

15.         format.

16.    </audio>

17. </figcaption>

18. </figure>

CSS source code:

1. #figaudio1 {

2.     width : 420px;;

3.     text-align:center;

4.     padding : 6px;

5.     background : white;

6.     margin : 0 11px 0px 0;

7.     border :solid 1px #888888;

8.     border-radius : 8px ;
9. }

10.  

11. #figcptionaudio1 {

12.     font-size : .8em;

13.     padding : 6px 8px;

14.     background : #dddddd;

15.     display :block;

16.     text-align :center;

17.     font-family : georgia, serif;

18.     font-style : italic;

19.     border-radius : 7px ;

20. }

21.  

22. #figaudio1 > img {

23.     background : #eeeeee;

24.     padding : 5px;

25.     border : solid 1px #444444;

26. }

27.  

28. /* For audio and img transitions/animation */

29. audio, #figaudio1 > img {

30.     transition:all 0.5s;

31. }
32.  

33. #figaudio1 > img:hover {

34.     box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);

35.     transform: scale(1.05);

36. }

37.  

38. audio:hover, audio:focus, audio:active {

39.     box-shadow: 15px 15px 20px rgba(0,0, 0, 0.4);

40.     transform: scale(1.05);

41. }
Changing the size of a video on the fly using CSS transforms
Resizing and rotating a video as the mouse pointer comes over it
See this example online (where you can modify the code on the fly) or just play the
following video, and move the mouse pointer in and out of the video while it's playing.

This example uses the pseudo CSS class :hover in order to track


the mouseover event. On mouseover, it uses a CSS transition property that
interpolates the changes in the scale and orientation of the video element (done
using a transform CSS property).

The corresponding HTML source code is:

1. <video id="w3devCampusVideo" autoplay controls>

2.

3.      <source src=https://mainline.i3s.unice.fr/mooc/samuraiPizzacat.webm

4.              type=video/webm>

5.      <source src=https://mainline.i3s.unice.fr/mooc/samuraiPizzacat.ogg

6.              type=video/ogg>

7.      <source src=https://mainline.i3s.unice.fr/mooc/samuraiPizzacat.mp4
8.              type=video/mp4>

9. </video>

... and the CSS source code is as follows:

1. #w3devCampusVideo {

2.     width: 300px;

3.     transition: all 0.5s ease-in-out;

4. }

5.  

6. #w3devCampusVideo:hover {

7.     width:400px;

8.     transform:rotate(-5deg);

9. }
Fullscreen video that resizes and maintains ratios. Uses simple JavaScript to modify CSS
properties
This is a trendy way of displaying videos. For a while, the PayPal Web site used
a small size video that looped and started playing as soon as the page was loaded.
One of the JsBin examples below uses this video. 
Below you will find two examples that show how to do this trick. The first is for a
"regular" video, using the <video> and <source> elements. This technique
can also be used on any YouTube embedded videos (see Example 2 below).

The interesting part is that we use a 100% standard (and really small and simple)
JavaScript code here to handle the window resize events and we just set regular
CSS properties width and height of the video element, to resize the video.

Example #1: with a regular video

 Online at JS Bin
Here is the HTML code. It's really simple, just notice the <body
onload="init();"> which calls the JavaScript init() function right after the
page is loaded.

1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4.     <meta charset="utf-8">

5.     <title>Full width video like PayPal site</title>

6. </head>

7. <body onload="init();">

8.     <video id="myVideo" autoplay>

9.       <source

10.           src=https://mainline.i3s.unice.fr/mooc/samuraiPizzacat.webm
11.           type=video/webm>

12.       <source

13.           src=https://mainline.i3s.unice.fr/mooc/samuraiPizzacat.ogg

14.           type=video/ogg>

15.       <source

16.           src=https://mainline.i3s.unice.fr/mooc/samuraiPizzacat.mp4

17.           type=video/mp4>

18.     </video>

19. </body>

Here is the CSS (remove margins, remove padding, hide parts that could overflow
from the <body>):

1. body {

2.     margin:0;

3.     padding:0;

4.     overflow:hidden;

5. }

And now the JavaScript code:

1. var video;

2.  

3. function init() {

4.    // function called when the page is loaded

5.

6.    video = document.querySelector("#myVideo");
7.

8.    // For initial value

9.    video.width = window.innerWidth;

10.    video.height = window.innerHeight;

11.

12.    // For dealing with window resize

13.    window.onresize = function() {

14.        video.width = window.innerWidth;

15.        video.height = window.innerHeight;

16.    };

17. }
Example #2: with a YouTube video

 Online at JS Bin

The CSS and JavaScript codes for this example are exactly the same as in Example
#1.
Full screen video, pure CSS approaches

1. Let's use the video from the PayPal Web site, played full screen using only very simple CSS.

In this example (online at JSBin), the video does not rescale; it's just cropped if the
browser window is resized. Enlarge your browser and you'll see a man with a phone
on the right. Resize your browser and you'll see only part of the video.
CSS code:

1. body {

2.   margin:0;

3.   padding:0;

4.   overflow:hidden;

5. }

6.  

7. video {

8.   width:100%;

9.   height:auto;

10. }

2. Full screen video with CSS effects


This time the video is zoomed in so that it's much bigger than the browser's window.
When we resize the browser, the part of the video that is visible adapts itself. It's not
"real resize" of the video.

Try the example and read the explanation in this article by Dudley Storey. Also
available as a simplified JsBin example.

HTML code:

1. <!DOCTYPE html>

2. <html lang="en">

3. <head>

4.    <meta charset="utf-8">

5.    <title>Full screen video, example from demosthene.info by </title>


6. </head>

7. <body>

8. <header>

9.  <video autoplay loop=""

10.   poster="https://mainline.i3s.unice.fr/mooc/polina.jpg"

11.   id="bgvid">

12.     <source src="https://mainline.i3s.unice.fr/mooc/polina.webm"

13.             type="video/webm">

14.     <source src="https://mainline.i3s.unice.fr/mooc/polina.mp4"

15.             type="video/mp4">

16.  </video>

17. </header>

18. <section>

19. <h1>https://demosthenes.info/blog/777/Create-Fullscreen-HTML5-Page-

20. Background-Video</h1>

21. </section>

22. </body>

23. </html>

CSS code:

1. html, body{

2.     color:white;

3.     height: 100%;

4. }
5.

6. header{

7.     height: 100%;

8.     background-image: url('https://dupontcours.free.fr/IMG/dots.png'),                           
url('#');

9.     background-repeat: repeat, no-repeat;

10.     background-size: auto, cover;

11.     background-position: center center, top left;

12.     font-family: sans-serif;

13.     color: #051a00;

14. }

15.  

16. header video {

17.     position:fixed;

18.     top:50%;

19.     left:50%;

20.     min-width:100%;

21.     min-height:100%;

22.     width:auto;

23.     height:auto;

24.     z-index:-100;

25.     transform:translateX(-50%) translateY(-50%);

26. }
The trick here is that:

1. the video is in the header, and the header has a plotted transparent background that is repeated in X
and Y (see lines 8 and 9).

2. The video is positioned so that it's origin (top left corner) is away from the visible surface (line 25),
while it is set to take 100% of the surface (lines 20 and 21).

Full screen video that resizes and keeps its ratio, using the viewport units.

Example on JsBin

This time we obtain the same result as with the first example that used JavaScript
and a resize event. The video resizes correctly and keeps its ratio.

CSS code:

1. body {

2.    margin: 0;

3. }

4.  

5.  

6. video {

7.    position: absolute;

8.    width: 100vw;

9.    height: 100vh;

10.    object-fit: cover;

11.    object-position: center center;

12. }
Discussion: why can't we achieve perfect resizing with only CSS
and the use of properties width=100% and height=100%?
Let's use the same video to compare the different approaches again:
1. Original approach, using JavaScript. This solution works on any browser, so we will focus on
the two following methods, based on pure CSS.

2. Using CSS 100% width and height properties (no JavaScript).

3. Using CSS viewport units for width and height (no JavasScript).

Resizing the browser window shows that #1 (JavaScript) and #3 (viewport units)
behave in the same way: the width or height of the video always fills the window
(whichever is smaller), and we always see the whole video.

Conclusion: we can get full size video without JavaScript by using viewport
units, unless we need to support some old browsers (see their current support
on CanIUse).

Setting the video to 100% width and height results in different behavior:

o 100% means 100% of the size of the <body> tag.

o The body tag's width is 100% of the browser window width, so the video is always full width.

o The body tag's height, however, is determined by the size of its children: the body tag's
height grows and shrinks to accommodate the size of the children.

o If the browser window is made wide and short, the video is full width, the height is taller than
the window, and part of the video is not visible. It seems that just using % does not get us the
same effect.

Knowledge check 2.2.4 (not graded)


0 points possible (ungraded)

Using CSS, is it possible to apply geometric transformations to a video player, or to add


shadows to an audio player?

Yes

No
non répondu

The <video> element has methods, properties/attributes and events that can be


manipulated with JavaScript. Using the DOM API, it's possible to manipulate an
audio or video element as a JavaScript object that has:

o Methods for controlling the behavior, such as play(), pause(), etc.


o Properties (duration, current position, etc.), either in read/write mode (such as volume), or in
read-only mode (such as encoding, duration, etc.)

o Events generated during the life cycle of the element that can be processed using
JavaScript callbacks. It is also possible to send events to control the video player

Like any HTML element, the <video> element can be manipulated/created using the


DOM JavaScript API. Here is an example of
programmatically creating a <video> element:

1. var video = document.createElement('video');

2. video.src = 'video.mp4';

3. video.controls = true;

4. document.body.appendChild(video);

This will create a complete video player for the file "video.mp4", with control buttons,
and will add it to the <body> element of the page.

Example that shows how to call play/pause or rewind a video


Please look at this interesting example  (you can click on "edit in JsBin" to view the
source, but we will give simpler and more detailed examples in the next section - this
one is more to show what can be done).
Note that in order to play the video, you must click on the "vid.play()" text. To pause
it, you click on the "vid.pause()" text, and so on. Notice the text at the top of the
video, as well as the transparency. The text can be selected, since all the elements
displayed are pure DOM objects. You can zoom the page in and out, etc. This was
not possible with the Flash technology.

Conclusion:  you can very easily change the look and feel of the standard video
player: use custom CSS and design your own control widgets. We can find many
examples of such video players that offer extended functionalities on the Web. We
will present some of them later in the course, but before that, let's see a little more of
what we can do using the JavaScript API of the <video> element.

Knowledge check 2.2.5 (not graded)


0 points possible (ungraded)

Once created or selected using the standard DOM API, can audio and video elements be
manipulated as JavaScript objects?
Yes

No
non répondu

Methods, properties, and events


The JavaScript API gives you powerful tools to manipulate the <video> element, as
the video object provides many properties, methods and events.

The complete list of events can be found in the HTML5 living standard specification.

The list of properties can be found at the W3C HTML5 Video Events and API page.
This page is interesting for Web developers because it shows an interactive view of
the different values and events changing over time while the video is playing within
the page.

Click on the picture below to see it running online (or try the direct link), then play
with the different buttons and look at the table of events and properties that will
change in real time. The displayed names show the properties, events, and methods
from the API.
Here is a table that shows the most interesting methods, properties, and events provided by
the <video> element API

We provide this as a quick reminder - keep in mind that the complete list is much
longer! 

Methods Properties
play() currentSrc pla

pause() currentTime pau

load() startTime (readonly) pro

canPlayType() videoWidth erro

videoHeight time

duration (readonly) end

ended (readonly) abo

error emp

paused (readonly) emp

muted wait

seeking load
volume

height

width

seekable (readonly)

played (readonly)

Let's see now, through a set of examples, how to use these most important
properties, methods, and events...

Knowledge check 2.2.6 (not graded)


0 points possible (ungraded)

The W3C specification about the JavaScript API associated


to  <audio>  and  <video>  elements, proposes an interactive demonstration of the
different properties/methods/events; it's a must see for all Web developers interested
in multimedia. Try it and guess what properties indicate the length of the video in
seconds and the name of a valid event that is sent while the video is being played...
duration and timeupdate

currentTime  and  play

The JavaScript API is useful for implementing playlists, making custom user
interfaces and many other interesting things. The "enhanced HTML5 multimedia
players" lesson presented further on the course relies heavily on this API.

Example #1: how to use external buttons to control the player's


behavior
This example shows the first steps towards writing a custom video player. It shows
basic usage of the JavaScript API for adding custom buttons to play/pause the video
or to go back to the beginning by setting the currentTime property to zero.
Try it online, and look at the source code below.

Source code extract:

1. <video id="vid" controls>

2. <source src=https://mainline.i3s.unice.fr/mooc/samuraiPizzacat.webm

3.          type=video/webm>

4. ...

5. </video>

6. <p>Example of custom controls:</p>

7. <button onclick="playVideo();" style="cursor: pointer;">Play</button>
8.  

9. <button onclick="pauseVideo();" style="cursor: pointer;">Pause</button>

10.  

11. <button onclick="rewindVideo();" style="cursor: pointer;">

12.        Back to beginning</button>

13. <script>

14.     vid = document.querySelector("#vid");

15.

16.     function playVideo() {

17.        vid.play();

18.   }

19.     function pauseVideo() {

20.        vid.pause();

21.   }

22.

23.     function rewindVideo() {

24.        vid.currentTime = 0;

25.   }

26. </script>
 

Explanations:

o Lines 7, 9 and 11: we add a click listener to each button, in order to call a JavaScript function
when the button is clicked.
o Line 14: using the DOM API we get the JavaScript object that corresponds to the video
element we inserted in the HTML document. This line is outside a function, it will be executed
when the page loads.

o Lines 17 and 20: we call methods from the API for playing/pausing the video.

o Line 24: we modify the currentTime property in order to rewind the video. Note


that vid.load() also rewinds the video, shows the poster image again, but also pauses the
video. By using currentTime=0 the playback does not stop.

Example #2: how to detect the end of a video and start another
one
This example listens for the ended event, and calls a callback function when the
video is ended.

1. <video src="video.ogv" id="myVideo">

2.     video not supported

3. </video>

4.

5. <script type='text/javascript'>

6.   var vid = document.querySelector('#myVideo');

7.   vid.addEventListener('ended', playNextVideo, false);

8.

9.   function playNextVideo(e) {

10.      // Whatever you want to do after the event, change the src attribute

11.      // of the video element, for example, in order to play another video

12.   }

13. </script>
Example #3: how to manage playlists
This example detects the end of a video then loads the next video, changes
the src attribute of the video element and plays the video (see the online example). 
To try this example: use the progress cursor to go near the end of the first video that is being
played and see how it continues with the next video. 

1. <!doctype html>

2. <html lang="en">

3.   <head>

4.     <meta charset="utf-8"/>

5.     <title>Sequential Movies</title>

6.     <script>

7.       var myVideo;

8.       var currentVideo = 0;

9.       var sources = [

10.         "https://mainline.i3s.unice.fr/mooc/samuraiPizzacat.mp4",

11.         "https://www.archive.org/download/AnimatedMechanicalArtPiecesAtMit/
P1120973_512kb.mp4"

12.         ];

13.

14. // Set the src of the video to the next URL in the playlist

15. // If at the end we start again from beginning (the modulo

16. // source.length does that)

17.       function loadNextVideo() {

18.         myVideo.src = sources[currentVideo % sources.length]

19.         myVideo.load();

20.         currentVideo++;

21.       }
22.

23. // listener plays the video

24.     function loadAndplayNextVideo() {

25.       console.log("playing " + sources[currentVideo % sources.length])

26.       loadNextVideo();

27.       myVideo.play();

28.

29.     }

30.

31. // Called when the page is loaded

32.     function init(){

33. // get the video element using the DOM api

34.     myVideo = document.querySelector("#myVideo");

35.

36. // Define a callback function called each time a video ended

37.     myVideo.addEventListener('ended', loadAndplayNextVideo, false);

38.

39. // Load the first video when the page is loaded.

40.     loadNextVideo();

41.     }

42.   </script>

43. </head>

44. <body onload="init()">
45.     <video id="myVideo"

46.       controls>

47.     </video>

48. </body>

49. </html>

 Line 9: the JavaScript array that contains the URLs of the videos in the playlist. In this
example, we've got only two of them, but if the array is larger the example will still work.

 Line 44: When the page is loaded, an init() function is called.

 Lines 34-40: we used the DOM to get the JavaScript object corresponding to the video
element, then define a listener for the ended event. Each time a video will end,
the loadAndplayNextVideo() callback will be called. As the video element has no src
attribute by default, we also preload the first video (call to loadNextVideo() at line 38).

 Lines 17-21: the loadNextVideo() function uses a variable called currentVideo that


corresponds to the index of the current video. By setting myVideo.src = sources
[currentVideo % sources.length], we set the src of the video element to sources[0],
then to sources[1], and as we increment the currentVideo index each time (line 19), if it
becomes greater than 1, the modulo (the "%" symbol is the modulo in JavaScript) will make it
"loop" between 0 and the number of videos in the playlist. In other words, when the last video
ends, it starts back to the first one.

In this section, we propose five extended examples that use more JavaScript and
more complex CSS manipulation. They might be a little hard to understand if you are
a JavaScript beginner, but don't be afraid to try and test them, look at the code, etc.

Some examples are given "as is", such as the custom video player that uses SVG (at
the end of the page); if you are interested, you may view the code. 

Example #1: a player showing the use of every type of CSS3


transformation
Please see this example online, originally written by Chris Heilmann, and tuned by
us ;).

Don't forget to click the JavaScript and CSS tabs in JS Bin in order to display the
JavaScript code that creates the buttons on the right of the video, and the CSS that
processes the different clicks and applies CSS3 transforms.
This example shows a lot:

o It uses the HTML5 elements <nav>, <footer>, <header>.

o It shows the use of CSS3 2D transformations (scale, translate, and rotate).

o It shows how to handle DOM events using JavaScript and how to modify CSS properties of
the <video> element from JavaScript.

Example #2: how to track all possible events and manipulate


many properties
This example also shows how to handle failures. See the code and play with
this example online.
Here is an example of a piece of code for handling errors during video playback:

1. ...

2.

3. vid.addEventListener('error', function(evt) {
4.     logEvent(evt,'red');

5. }, false);

6.

7. ...

8.

9. function logEvent(evt, color) {

10.     switch (evt.type) {

11.        ...

12.        case 'error':

13.            var error = document.querySelector('video').error;

14.

15.            switch (error.code) {

16.              case error.MEDIA_ERR_ABORTED:

17.                 note.innerHTML = "fetching aborted at the user's request";

18.                 break;

19.              case error.MEDIA_ERR_NETWORK:

20.                 note.innerHTML = "a network error caused the browser to stop fetching the
media";

21.                 break;

22.              case error.MEDIA_ERR_DECODE:

23.                 note.innerHTML = "an error occurred while decoding the media";

24.                 break;

25.              case error.MEDIA_ERR_SRC_NOT_SUPPORTED:
26.                 note.innerHTML = "the media indicated by the src

27.                                   attribute was not suitable";

28.                 break;

29.              default:

30.                 note.innerHTML = "an error occurred";

31.                 break;

32.            }

33.            break;

34.        }

35.  ...

36. }
Example #3: how to display a percentage of buffering when using
a slow connection
See the example online here too.
Note that on mobile phones, the video does not start until the user presses the play
control or clicks on the video picture. Using the "canplaythrough" event is a trick
to call a function that starts the video player as soon as the page is loaded on
desktop. This event is not supported by mobile devices, so if you try this example on
a mobile, the video will not start automatically.

As explained by the Apple Developer Web site:  "The buffered property is


a TimeRanges object: an array of start and stop times, not a single value. Consider
what happens if the person watching the media uses the time scrubber to jump
forward to a point in the movie that hasn’t loaded yet—the movie stops loading and
jumps forward to the new point in time, then starts buffering again from there. So
the buffered property can contain an array of discontinuous ranges. The example
simply seeks the end of the array and reads the last value, so it actually shows the
percentage into the movie duration for which there is data. "

1. <!doctype html>
2. <html lang="en">

3.   <head>

4.     <title>JavaScript Progress Monitor</title>

5.     <meta charset="utf-8"/>

6.     <script>

7.       function getPercentProg() {

8.           var myVideo = document.getElementsByTagName('video')[0];

9.           var endBuf = myVideo.buffered.end(0);

10.           var soFar = parseInt(((endBuf / myVideo.duration) * 100));

11.           document.getElementById("loadStatus").innerHTML = soFar + '%';

12.    }

13.

14.       // Will be called as soon as the page is ready on desktop computer,

15.       // Only when a user clicks on play control or image on mobile

16.       function myAutoPlay() {

17.           var myVideo = document.getElementsByTagName('video')[0];

18.           myVideo.play();

19.    }

20.

21.       function addMyListeners(){

22.           var myVideo = document.getElementsByTagName('video')[0];

23.           myVideo.addEventListener('progress', getPercentProg, false);
24.

25.           // Calls autoplay only if the device is adapted

26.           myVideo.addEventListener('canplaythrough', myAutoPlay, false);

27.    }

28.   </script>

29. </head>

30. <body onload="addMyListeners()">

31.     <h1>Check progression of buffering before playing a movie. Useful withy

32.         slow connexion (3G, etc.)</h1>

33.     <div>

34.       <video controls>

35.           <source src=https://html5doctor.com/demos/video-canvas-magic/video.webm

36.                   type=video/webm>

37.           <source src=https://html5doctor.com/demos/video-canvas-magic/video.ogg  

38.                   type=video/ogg>

39.           <source src=https://html5doctor.com/demos/video-canvas-magic/video.mp4

40.                   type=video/mp4>

41.       </video>

42.       <p id="loadStatus">Buffering...</p>

43.     </div>

44. </body>

45. </html>
Example #4: how to use SVG elements as external controllers
This is the ultimate way of doing a real custom player: redesign your own controls
using SVG shapes! This example (try it online) is given "as is" for those of you
who may be curious.

Example #5: a custom video player written by a previous student


This is more an example than a tutorial. Maurice, a student who followed the
precursor version of this MOOC, had the assignment to write a custom video player
with playlist, video thumbnails, custom play/pause/next/previous/volume controls,
and present it in a Web page that used a nice layout based on the new structuring
elements seen during Week 1.

Here is the online example on JS Bin, by Maurice Buiten. We recommend that you
look at the source code.

Screenshot:
his section introduces the HTML5 <track> element, useful for adding closed
captions, subtitles, descriptions, and metadata to your videos. It comes with a new
JavaScript API.

The WebVTT format used for describing a track file is also presented in this chapter.

Most of the major desktop browsers support HTML5 captioning


Please check the browser support related to the <track> element support by
browsers.

Some definitions

o closed captions describe all relevant audio present in the video (fire, rain, birds, gun fights,
etc.).
o subtitles are only for spoken words.

The accessibility features of TV programs often propose both options for people with hearing
deficiencies. 

Typical use: add a subtitle/caption track to a <video> element


Important warning!!

The <track> element cannot be used with a file:// URL. Please


use https:// and a Web server. Your server must use a special MIME format for
the .vtt files: text/vtt;charset=utf-8 (set by default on most servers
now).

Examples of the lines to add to an Apache Web server:

1. <Files mysubtitle.vtt>

2. ForceType text/vtt;charset=utf-8

3. </Files>
Here is an example on JsBin of a video element that includes a <track> element in
the .vtt (WebVTT) format (line 9 in the source code shown below), .

As seen in this screenshot, the example uses a <track> element to insert


basic captions to the video: sounds and music are described, in addition to
standard subtitles that correspond to what the different movie characters say.

1. <video height="272" width="640"
2.        poster="https://mainline.i3s.unice.fr/mooc/q1fx20VZ-640.jpg"

3.        crossorigin="anonymous"

4.        controls>

5.    <source src="https://mainline.i3s.unice.fr/mooc/sintel.mp4"

6.            type="video/mp4">

7.    <source src="https://mainline.i3s.unice.fr/mooc/sintel.webm"

8.            type="video/webm">

9.    <track src="https://mainline.i3s.unice.fr/mooc/sintel-captions.vtt"

10.           kind="captions" label="Closed Captions" default>

11. </video>

Notice that the <track> element at line 9 has an attribute named kind that


indicates the type of the track that is included. Possible values
are: subtitles, captions, descriptions, chapters or metadata.

 The <track> element also has an attribute default that indicates that we want this track


to be displayed by default when reading the video.

We also used  an attribute named crossorigin that is necessary just to run this


demo, as it is required by the server that hosts the video from this example.

Multiple tracks may be included in a video element


Multiple tracks are needed to support different langages, video captions for the
hearing-impaired, subtitles, etc.

Below is an example (from the specification) that includes


multiple <track> elements (subtitles for three languages and captions only for
English):

1. <video src="brave.webm">

2.    <track kind=subtitles src=brave.en.vtt

3.           srclang=en

4.           label="English">
5.    <track kind=captions src=brave.en.hoh.vtt

6.           srclang=en

7.           label="English for the Hard of Hearing">

8.    <track kind=subtitles src=brave.fr.vtt

9.           srclang=fr

10.           lang=fr 

11.           label="Français">

12.    <track kind=subtitles src=brave.de.vtt

13.           srclang=de

14.           lang=de

15.           label="Deutsch">

16. </video>

Note the use of some new attributes in the <track> element:

o label: the label value will be displayed in the GUI control that is included in the default
HTML5 video player,

o srclang:  gives the language for the text track data. The value must be a valid BCP 47
language tag. This attribute must be present if the element's kind attribute is in
the subtitles state.

External resources

o From the HTML specification: The track element

o From the W3C specification:  WebVTT: The Web Video Text Tracks Format

o From MDN's Web Docs: WebVTT and Adding captions and subtitles to HTML5 video

o An article from 3playmedia: How to create a WebVTT file

Knowledge check 2.3.1 (not graded)


0 points possible (ungraded)
What is the name of the element we must include inside a <video> element, in order
to display captions and subtitles? Just type the name of the element, without < or >
characters.

Let's look at a simple example. First, you need a video on one of the formats/codecs
supported by the browsers you target. A recommended codec is H264, but other
formats, such as webm, may have some advantages if the browser supports them.
For example, webm allows the video to start playing after a much shorter buffering
time. In other words, try if possible to provide the video encoded with more than one
codec.

For this, use any sort of open source, free or commercial video encoding software,
such as Handbrake (free, open source) or Super (free). There are also online video
encoding services, and you can even upload your video to YouTube, let it encode
your video in several resolutions and codecs, and use a browser extension such
as Video DownloadHelper (for Firefox) to download the video in your chosen formats.

So, let's suppose you have a video like the one below (we included it on YouTube for
practical reasons). This video has subtitles (you can activate them in the YouTube
player), but the goal of this lesson is to explain how we made them without using the
YouTube embedded tools, which do not allow export the subtitle file to be exported in
the webVTT format.

And you've also got it in mp4/H264 and in webm formats. Here is how you can


embed it in your page using the video element:

1. <video id="myVideo" width=500 controls>

2.   <source  

3.       src="videos/SameOldSongAndDanceRogerLathaudPart1MidRes.mp4"

4.       type="video/mp4">

5.   <source   

6.       src="videos/SameOldSongAndDanceRogerLathaudPart1MidRes.webm"

7.       type="video/webm">

8.  

9.   <track src="videos/subtitles.vtt"   
10.          kind="subtitles" srclang="en" default>

11. </video>

At line 9, we added a <track> element to add English subtitles, as the guitar


teacher there is speaking in French. We will now explain how we created this subtitle
track.

Adding subtitles to the video


Now, we need to create a WebVTT file for this video. How can we synchronize an
English translation of what the guitar teacher says in French?

Many tools - both free and commercial - are available to add subtitles to a video.
Most are native applications you need to install on your computer. However, a free
and very practical tool is available for doing this 100% in a Web browser: amara.

Go to the above Web site, click on the "subtitle a video" link, then follow the different
tutorials/instructions. It will ask for a YouTube URL, so it's better to first upload your
video to YouTube (even in private mode). Once you have entered the URL of your
video, you will have an online subtitles/caption editor. Enter your subtitles and sync
them until you are happy with the results.
Once your subtitles/captions are ok, you will be able to upload them to YouTube, or -
this is what we wanted first- download them as WebVTT format:
Try your subtitled/captioned video
Let's look at a simple example. First, you need a video on one of the formats/codecs
supported by the browsers you target. A recommended codec is H264, but other
formats, such as webm, may have some advantages if the browser supports them.
For example, webm allows the video to start playing after a much shorter buffering
time. In other words, try if possible to provide the video encoded with more than one
codec.

For this, use any sort of open source, free or commercial video encoding software,
such as Handbrake (free, open source) or Super (free). There are also online video
encoding services, and you can even upload your video to YouTube, let it encode
your video in several resolutions and codecs, and use a browser extension such
as Video DownloadHelper (for Firefox) to download the video in your chosen formats.

So, let's suppose you have a video like the one below (we included it on YouTube for
practical reasons). This video has subtitles (you can activate them in the YouTube
player), but the goal of this lesson is to explain how we made them without using the
YouTube embedded tools, which do not allow export the subtitle file to be exported in
the webVTT format.

And you've also got it in mp4/H264 and in webm formats. Here is how you can


embed it in your page using the video element:

1. <video id="myVideo" width=500 controls>

2.   <source  

3.       src="videos/SameOldSongAndDanceRogerLathaudPart1MidRes.mp4"

4.       type="video/mp4">

5.   <source   
6.       src="videos/SameOldSongAndDanceRogerLathaudPart1MidRes.webm"

7.       type="video/webm">

8.  

9.   <track src="videos/subtitles.vtt"   

10.          kind="subtitles" srclang="en" default>

11. </video>

At line 9, we added a <track> element to add English subtitles, as the guitar


teacher there is speaking in French. We will now explain how we created this subtitle
track.

Adding subtitles to the video


Now, we need to create a WebVTT file for this video. How can we synchronize an
English translation of what the guitar teacher says in French?

Many tools - both free and commercial - are available to add subtitles to a video.
Most are native applications you need to install on your computer. However, a free
and very practical tool is available for doing this 100% in a Web browser: amara.

Go to the above Web site, click on the "subtitle a video" link, then follow the different
tutorials/instructions. It will ask for a YouTube URL, so it's better to first upload your
video to YouTube (even in private mode). Once you have entered the URL of your
video, you will have an online subtitles/caption editor. Enter your subtitles and sync
them until you are happy with the results.
Once your subtitles/captions are ok, you will be able to upload them to YouTube, or -
this is what we wanted first- download them as WebVTT format:
Try your subtitled/captioned video

You might also like