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>

The this Keyword

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.

Inline mouse hover JavaScript example
Figure 20-2. Inline mouse hover JavaScript example

Note

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.

Attaching Events to Objects in a Script

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.

Example 20-7. Noninline ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.