jQuery in Action
86
CHAPTER 4
Events are where it happens!
<body>
<img id="vstar" src="vstar.jpg"
onclick="say('Vroom vroom!');"/>
<div id="console"></div>
</body>
</html>
In this example, we employ both styles of event handler declaration: declaring
under script control and declaring in a markup attribute.
under script control and declaring in a markup attribute.
The page first declares a ready handler
b
in which a reference to the image
element with the
id
of
vstar
is obtained (using jQuery), and its
onmouseover
prop-
erty is set to a function instance that we declare inline. This function becomes the
event handler for the element when a mouseover event is triggered on it. Note
that this function expects a single parameter to be passed to it. We'll learn more
about this parameter shortly.
event handler for the element when a mouseover event is triggered on it. Note
that this function expects a single parameter to be passed to it. We'll learn more
about this parameter shortly.
We also declare a small utility function,
say()
c
, that we use to emit text mes-
sages to a
<div>
element on the page
e
. This will save us the trouble of nuisance
alerts to indicate when things happen on our page.
In the body of the page (along with the console element), we define an image
element
d
on which we'll define event handlers. We've already seen how to
define one under script control in the ready handler
b
, but here we declare a
handler for a click event using the
onclick
attribute of the
<img>
element.
Loading this page into a browser (found in the file chapter4/dom.0.events.
html), waving the mouse pointer over the image a few times, and then clicking
the image result in a display similar to that shown in figure 4.1.
the image result in a display similar to that shown in figure 4.1.
We declare the click event handler in the
<img>
element markup using the fol-
lowing attribute:
onclick="say('Vroom vroom!');"
This might lead us to believe that the
say()
function becomes the click event han-
dler for the element, but that's not the case. When handlers are declared via
markup attributes, an anonymous function is automatically created using the value
of the attribute as the function body. The action taken as a result of the attribute
declaration is equivalent to (assuming that
markup attributes, an anonymous function is automatically created using the value
of the attribute as the function body. The action taken as a result of the attribute
declaration is equivalent to (assuming that
imageElement
is a reference to the
image element) the following:
imageElement.onclick = function(event) {
say('Vroom vroom!');
}
<img> element is
instrumented
instrumented
d
<div> element
serves as console
serves as console
e