PHP

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
<!DOCTYPE HTML PUBLIC
              "-//W3C//DTD HTML 4.01 Transitional//EN"
              "http://www.w3.org/TR/html401/loose.dtd">
<html>
<head>
<title>MouseOver Example</title>
</head>
<body bgcolor="#ffffff">
<a href="add_to_cart.php"
  onMouseOut="cart.src='cart_off.jpg'"
  onMouseOver="cart.src='cart_on.jpg'">
<img src="cart_off.jpg" border=0 name="cart"
     alt="cart picture"></a>
</body>
</html>

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:

onMouseOver="cart.src='cart_on.jpg'"

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:

onMouseOut="cart.src='cart_off.jpg'"

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.

by BrainBellupdated
Advertisement: