O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required