JavaScript Tips and Tricks

In this section we present other common tools implemented with JavaScript that aren't particular to web database applications. Examples include:

  • Mouse rollovers, where an image is changed to highlight an option as the mouse cursor passes over it

  • Calculating and updating <form> fields based on user changes to data

  • Interacting with the web browser and windows to trigger events and manipulate presentation

  • Detecting which browser application and version the user is using

Rollover presentation with mouseOver events

Example 7-4 shows a basic implementation of the common rollover feature used in many web applications.

Example 7-4. mouseOver example with JavaScript
              "-//W3C//DTD HTML 4.01 Transitional//EN"
<title>MouseOver Example</title>
<body bgcolor="#ffffff">
<a href="add_to_cart.php"
<img src="cart_off.jpg" border=0 name="cart"
     alt="cart picture"></a>

When the page is first loaded, an image of a shopping cart in plain gray off-mode is shown; the image is used in the front page of the winestore. As usual, the image is loaded with the HTML fragment:

<img src="cart_off.jpg" border=0 name="cart">

The only difference to the usual approach of loading images is that the <img> tag has a name attribute, in this case name="cart".

If the mouse passes over the cart image, an onMouseOver event is generated, and the JavaScript action carried out is:


The event handler changes the value of the src attribute of the <img> tag with the name="cart". The result is that a new image is loaded to replace the off-mode image with an on-mode image. In this case, a shopping cart with a blue foreground is shown.

When the mouse leaves the image region, the onMouseOut event is generated and handled with the following JavaScript fragment:


This restores the original gray off-mode image. The impression to the user is that the cart element is highlighted as the user focuses on the element; the same technique is used to highlight menu options and to produce pop-up and pull-down menus.