Inline JavaScript

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).

Example 20-6. Using inline JavaScript
<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.

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.

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.