HTML Avancer
HTML Avancer
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:
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 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.
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.
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...
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.
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
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".
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):
Section that contains the main navigation links (within the document or
to other pages).
<nav>
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:
nav
footer
title
header
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"/>
6. </head>
7. <body>
8. <header>
9. <h1>Simple <span>HTML5</span> blog</h1>
10. </header>
11. ...
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"/>
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>
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. }
11. margin-left: 0
12. }
14. margin-left: -15px
15. }
17. padding: 3px 15px 4px
18. }
20. background: #722;
21. color: #fff
22. }
A <section> for each month and an <article> for each post in the blog
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. }
13. font-size: 1em;
14. padding: 0;
15. }
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.
1. <section>
2. <article>
3. <header>
5. </header>
6.
9. to see the different inclusions of elements one in each other. If you
14. element, while the tag cloud on the right is a <aside> element. The
17. <figure>
18. <img src="HTML5-tags.png"
20. <figcaption>
22. be used. This page put a <nav> on top, and does not have
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"
4. <figcaption>
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.
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.
1. <html>
2. ...
3. <body>
4. ...
5. <section>
6. ...
7. </section>
8. <aside>
9. ...
10. </aside>
11.
12. <footer>
14. </footer>
15.
16. </body>
17. </html>
1. footer {
2. clear: both;
3. color: #777;
4. padding: 10px 50px
5. }
What is a figcaption?
An image link
A caption under a figure
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.
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>
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>:
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.
The HTML5 specification says that "each sectioning element potentially has a
heading and has also an outline associated".
1. <body>
2. <h1>Title of my document</h1>
3. ...
4. </body>
1. <body>
2. ...
3. <section>
4. <h1>Title of my section</h1>
5. ...
6. </section>
7. </body>
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.
1. <body>
2. <section>
4. ...
6. (lower rank)</h2>
7. ....
10. ...
13. ...
14. </section>
15. </body>
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.
3. ...
4. </section>
1. <section>
2. <header>
5. </header>
6. ...
7. </section>
1. <section>
2. <header>
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.
Notice that <body> is also a sectioning element. It's called a "sectioning root", and
would also need a heading.
1. <body>
2. <h1>Example Blog</h1>
3. <section>
4. <header>
7. </header>
9. </section>
10. </body>
In red, the sectioning root (<body>) and the sectioning elements
(<section> here...), each have a heading.
To sum up:
1. <section>
2. <header>
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>
5. </header>
1. <body>
2. <h4>Apples</h4>
4. <section>
5. <h2>Taste</h2>
7. <h6>Sweet</h6>
9. <h1>Color</h1>
11. </section>
12. </body>
1. <body>
2. <h1>Apples</h1>
4. <section>
5. <h2>Taste</h2>
7. <section>
8. <h3>Sweet</h3>
10. </section>
11. </section>
12. <section>
13. <h2>Color</h2>
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>
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.
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.
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>?
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. <!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.
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
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>.
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>
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.
1. <nav>
2. <header>
3. <h2>Navigation menu</h2>
4. </header>
5. ...
6. </nav>
Finally, the fixed example
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.
1. <header>
2. <code><header></code>
3. </header>
4.
5. <section>
6. <code><section> <br> float: left;</code>
7. </section>
8.
9. <aside>
11. </aside>
12.
13. <footer>
14. <code><footer></code>
15. </footer>
Example from the live coding video, a slight adaptation of the technique described above
Also available online at JSBin.
HTML code:
1. <header>
2. <code><header></code>
3. </header>
4.
5. <section>
6. <code><section> <br> float: left;</code>
7. </section>
8.
9. <section>
11. </section>
12.
13. <section>
15. </section>
16.
17. <footer>
18. <code><footer></code>
19. </footer>
External resources
Old but good article on "A List Apart" (ALA): CSS Floats 101
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:
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>
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).
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
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
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. }
1. details[open] summary:after {
2. content: "-";
3. color: #FFFFFF
4. }
Current browser support
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.
Example:
2.
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...
<time datetime="2020-11-13
09:00"> November 13th year 2020, time = 9:00
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.
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>
External resources:
The <mark> element
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>
9. </body>
10. </html>
Example 2:
Source code:
1. <body>
2. <pre>
3. <code><mark>var</mark> i = 3;</code>
4. </pre>
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 An article on Web Platform News: "The <mark> element could help make your text more
scannable"
To download a file
To highlight a text
To add a link
1. Content-type: text/html, text/plain, image/gif, image/jpg, etc.
1. <a href="toto.jpg">
...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 {
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.
13. response.setContentType("application/zip");
14. response.setHeader("Content-Disposition",
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".
1. <a href="normal.gif" download="MichelBuffa.gif">
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).
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:
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.
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 etc.
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...
...where all of the end of the sentence has been translated except the author's name.
1. <a href = "/images/batman_robin_car_superpower_007.rar"
2. download = "Batmobile.rar" >
4. </a>
___________________________________________________________________
__________
Batmobile.rar
batman_robin_car_superpower_007.rar
non répondu
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).
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">
11. </span>
12. </dd>
13. </dl>
16. <ul>
17. <li><a href="https://www.twitter.com/micbuffa"
19. <li><a href="https://www.blogger.com/micbuffa"
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.
5.
6. <dd itemprop="address" itemscope
7. itemtype="https://schema.org/PostalAddress">
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.
19.
20. ...
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 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 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.
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.
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>,
11. <a href="https://www.i3s.unice.fr/" itemprop="affiliation">I3S
13. email
14. is : <span itemprop="email">[email protected]</span>.
16. <span itemprop="address" itemscope
17. itemtype="https://schema.org/PostalAddress">
20. </span>
21. </div>
22. </body>
23. </html>
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.
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>
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.
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.
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
11. France
12. </span>
13. </dd>
14. </dl>
16. <ul>
17. <li><a href="https://www.twitter.com/micbuffa"
21. </ul>
22. </section>
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).
1. ...
2. </dl>
3.
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>,
13. itemtype="https://schema.org/Country">
15. </span>
16. </dd>
17.
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.
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">
3. <ul>
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.
If the itemprop attribute appears on a:
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.
For example, the value of a property defined in an <img> element will be the value of
the src 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 MicroData Generator
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.
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.
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 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.
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.
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
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
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.).
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):
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" /
>
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>
External resources
HTML5 comes with several ways of handling audio - what are they?
2 correct answers.
Here are the most common attributes you can use with the <video> element. They
are self explanatory...
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.
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 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.
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.
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 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).
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.
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" />
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>
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.
23. background : #eeeeee;
24. padding : 5px;
25. border : solid 1px #444444;
26. }
27.
30. transition:all 0.5s;
31. }
32.
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.
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>
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.
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">
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. }
1. var video;
2.
3. function init() {
5.
6. video = document.querySelector("#myVideo");
7.
9. video.width = window.innerWidth;
10. video.height = window.innerHeight;
11.
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. }
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">
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;
12. font-family: sans-serif;
13. color: #051a00;
14. }
15.
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;
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.
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).
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.
Yes
No
non répondu
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
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.
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.
Once created or selected using the standard DOM API, can audio and video elements be
manipulated as JavaScript objects?
Yes
No
non répondu
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
videoHeight time
error 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...
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.
1. <video id="vid" controls>
2. <source src=https://mainline.i3s.unice.fr/mooc/samuraiPizzacat.webm
3. type=video/webm>
4. ...
5. </video>
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;">
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.
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">
3. </video>
4.
5. <script type='text/javascript'>
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
17. function loadNextVideo() {
18. myVideo.src = sources[currentVideo % sources.length]
19. myVideo.load();
20. currentVideo++;
21. }
22.
24. function loadAndplayNextVideo() {
26. loadNextVideo();
27. myVideo.play();
28.
29. }
30.
32. function init(){
34. myVideo = document.querySelector("#myVideo");
35.
37. myVideo.addEventListener('ended', loadAndplayNextVideo, false);
38.
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.
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).
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.
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 shows how to handle DOM events using JavaScript and how to modify CSS properties of
the <video> element from JavaScript.
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:
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:
24. break;
25. case error.MEDIA_ERR_SRC_NOT_SUPPORTED:
26. note.innerHTML = "the media indicated by the src
28. break;
29. default:
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.
1. <!doctype html>
2. <html lang="en">
3. <head>
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.
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.
26. myVideo.addEventListener('canplaythrough', myAutoPlay, false);
27. }
28. </script>
29. </head>
30. <body onload="addMyListeners()">
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.
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.
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.
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), .
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"
11. </video>
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
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>
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 W3C specification: WebVTT: The Web Video Text Tracks Format
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.
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>
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.
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>
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