The DOM API stores data attribute values as strings (as implied by
the class DOMStringMap), meaning you cannot store object data.
jQuery extends the functionality of data attributes by providing an
interface that allows you to store objects as data attributes, which
We can also modify or add data attributes with JavaScript. For example, if we wanted
to highlight paragraphs with the word
giraffe and indicate that we want case-sensitive
matches, we might do this:
highlightActions
[
0
].
dataset
.
containing
=
"giraffe"
;
highlightActions
[
0
].
dataset
.
caseSensitive
=
"true"
;
Events
The DOM API describes almost 200 events, and each browser further implements
nonstandard events, so we certainly won’t discuss all events here, but we will cover
what you need to know about them. Let’s start with a very easy-to-understand event:
click
. We’ll use the
click
event to hook up our “highlight” button to our
highlightParas
function:
const
highlightActions
=
document
.
querySelectorAll
(
'[data-action="highlight"]'
);
for
(
let
a
of
highlightActions
) {
a
.
addEventListener
(
'click'
,
evt
=>
{
evt
.
preventDefault
();
highlightParas
(
a
.
dataset
.
containing
);
});
}
const
removeHighlightActions
=
document
.
querySelectorAll
(
'[data-action="removeHighlights"]'
);
for
(
let
a
of
removeHighlightActions
) {
a
.
addEventListener
(
'click'
,
evt
=>
{
evt
.
preventDefault
();
removeParaHighlights
();
});
}
Every element has a method named
addEventListener
that allows you to specify a
function that will be called when that event occurs. That function takes a single argu‐
ment, an object of type
Event
. The event object contains all the relevant information
about the event, which will be specific to the type of event. For example,
click
events
will have the properties
clientX
and
clientY
, which tell you the coordinates where
the click occurred, as well as
target
, which is the element that raised the
click
event.
The event model is designed to allow multiple handlers to handle the same event.
Many events have default handlers; for example, if the user clicks on an
<a>
link, the
browser will handle the event by loading the requested page. If you want to prevent
266 | Chapter 18: JavaScript in the Browser