Using Event Handlers

An event handler connects an action in the browser window to a JavaScript code, which in turn causes some reaction in the browser window.

In this example, when the visitor rolls the mouse over (onmouseover) a button graphic (Figure 12.6), the original graphic is replaced by an activated button graphic (Figures 12.7 and 12.8).

Figure 12.7. Before the image is rolled over.

Figure 12.8. After the image is rolled over.

To use an event handler:


<a href="#"

Start the tag to which you want to add an event handler. This typically will either be a link tag (<a>) or one of the form tags (Code 12.3).

Code 12.3. When the visitor moves the mouse over the area of the link containing the image (b_off.gif), that image changes its source to a different graphic (b_on.gif).

[View full width]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " xhtml1-strict.dtd"> <html xmlns=""> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>CSS, DHTML &amp; Ajax | Using Event Handlers</title> </head> <body> <p>      <a href="#"onmouseover="document.images.button01.src='/books/3/292/1/html/2/b_on.png';"      onmouseout="document.images.button01.src='/books/3/292/1/html/2/b_off.png';">      <img  src="/books/3/292/1/html/2/b_off.png" alt="Alice" />      </a> </p> </body></html>



In the tag you started in Step 1, type a relevant event handler from Table 12.3, followed by an equal sign (=).


"document.images.button01.src= 'b_on.png';"

Type an opening quote ("), the JavaScript you want executed when the event occurs, and a close quote (").

The JavaScript can be anything you want, including function calls. If you want to run multiple lines of JavaScript off a single event handler, separate the statements with a semicolon (;), but do not use a hard return.


onmouseout="document.images. button01.src='/books/3/292/1/html/2/b_off.png';"

Add as many event handlers as you want to the HTML tag by repeating Steps 2 and 3.



Type a closing chevron (>) to close the tag you started in Step 1.


<img src="/books/3/292/1/html/2/button_off.png" _ />

Add an image, text, or other HTML content that you want to have that visually tells the visitor where to act in order to trigger the event.



Type the closing tag for the tag you started in Step 1.


  • If you want a single event to perform multiple tasks, add each action inside the quotes, separating actions with a semicolon (;):

    onclick="action1; action2; action3;"

  • You can not only use event handlers to run JavaScript functions, but also include JavaScript statements directly inside the quotes.

CSS, DHTML and Ajax. Visual QuickStart Guide
CSS, DHTML, and Ajax, Fourth Edition
ISBN: 032144325X
EAN: 2147483647
Year: 2006
Pages: 230

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: