HTML and CSS Reference
In-Depth Information
FIGURE 4.6
The script
superimposes the caption
over the video as delectable
selectable text.
The data-* attributes (custom data attributes)
HTML5 allows custom attributes on any element. These can be used to pass information to local scripts.
Previously, to store custom data in your markup, authors would do something annoying like use classes:
<input class=”spaceship shields-5 lives-3 energy-75”>
. Then your script would need to
waste time grabbing these class names, such as
shields-5
, splitting them at a delimiter (a hyphen in this
example) to extract the value. In his book, PPK on JavaScript (New Riders, ISBN 0321423305), Peter Paul
Koch explains how to do this and why he elected to use custom attributes in some HTML4 pages, making
the JavaScript leaner and easier to write but also making the page technically invalid. As it's much easier
to use
data-shields=5
for passing name/value pairs to scripts, HTML5 legitimises and standardises this
useful, real-world practice.
We're using
data-begin
and
data-end
; they could just as legitimately be
data-start
and
data-finish
,
or (in a different genre of video)
data-ooh-matron
and
data-slapandtickle
. Like choosing class or id
names, you should pick a name that matches the semantics.
Custom data attributes are only meant for passing information to the site's own scripts, for which there are
no more appropriate attributes or elements.
The spec says “These attributes are not intended for use by software that is independent of the site that
uses the attributes” and are therefore not intended to pass information to crawlers or third-party parsers.
That's a job for microformats, microdata, or RDFa.
When the
data-*
attributes are fully supported in a browser, JavaScript can access the properties using
element.dataset.foo
(where the
data-foo
attribute contains the value). Support can be emulated
using JavaScript by extending the
HTMLElement
object, which typically isn't possible in IE9 alpha release
and below, which you can see here:
http://gist.github.com/362081
.
Otherwise scripts can access the val-
ues via the
get
/
setAttribute
methods. The advantage of the dataset property over
setAttribute
is
that it can be enumerated, but also, when fully implemented in browsers, setting a dataset attribute auto-
matically sets the content attribute on the element giving you a shorthand syntax for setting custom data.
For more information, see the spec
http://dev.w3.org/html5/spec/Overview.html#custom-data-attribute
.