Using <script>
tags isn’t
the only way you can execute JavaScript statements—you can also access
JavaScript from within HTML tags, which makes for great dynamic interactivity.
For example, to add a quick effect when the mouse pointer passes
over an object, you can use code such as that in the <img />
tag in Example 20-6, which displays an apple by default,
but replaces it with an orange when the mouse passes over (and restores
the apple when the mouse leaves).
<html> <head> <title>Inline JavaScript</title> </head> <body> <img src='apple.png' onmouseover="this.src='orange.png'" onmouseout="this.src='apple.png'" /> </body> </html>
In the preceding example you see the this
keyword in use. It tells the JavaScript
to operate on the calling object, namely the <img />
tag. You can see the result in
Figure 20-2, where the
mouse pointer is yet to pass over the apple.
When supplied from an inline JavaScript call, the this
keyword represents the calling object.
When used in class methods, the this
keyword represents an object to which
the method applies.
The preceding code is the equivalent of providing an ID to the
<img />
tag and then attaching
the actions to the tag’s mouse events, like in Example 20-7.
<html> <head> <title>Noninline JavaScript</title> <script src='OSC.js'></script> </head> <body> <img id='object' src='apple.png' /> <script> O('object').onmouseover = function() { this.src = 'orange.png' } O('object').onmouseout = function() { this.src = 'apple.png' } </script> </body> </html>
This code applies the ID of object
to the <img
/>
tag in the HTML section, then proceeds to manipulate it
separately in the JavaScript section by attaching anonymous functions to
each event.
Whether you’re using inline or separate JavaScript, there are several events to which you can attach actions, enabling a wealth of additional features that you can provide for your users. Table 20-2 lists these events, and details when they will be triggered.
Event | Occurs |
| When an image’s loading is stopped before completion |
| When an element loses focus |
| When any part of a form has changed |
| When an object is clicked |
| When an object is double-clicked |
| When a JavaScript error is encountered |
| When an element gets focus |
| When a key is being pressed (including Shift, Alt, Ctrl, and Esc) |
| When a key is being pressed (not including Shift, Alt, Ctrl, and Esc) |
| When a key is released |
| When an object has loaded |
| When the mouse button is pressed over an element |
| When the mouse is moved over an element |
| When the mouse leaves an element |
| When the mouse passes over an element from outside it |
| When the mouse button is released |
| When a form is submitted |
| When a form is reset |
| When the browser is resized |
| When the document is scrolled |
| When some text is selected |
| When a document is removed |