15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

346<br />

<strong>JavaScript</strong> <strong>Examples</strong> <strong>Bible</strong>: The Essential Companion to <strong>JavaScript</strong> <strong>Bible</strong><br />

Event handlers<br />

onClick<br />

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5<br />

Compatibility ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓<br />

Example<br />

Listing 24-1 demonstrates not only the onClick event handler of a button but<br />

also how you may need to extract a particular button’s name or value properties<br />

from a general-purpose function that services multiple buttons. In this case, each<br />

button passes its own object as a parameter to the displayTeam() function. The<br />

function then displays the results in an alert dialog box. A real-world application<br />

would probably use a more complex if...else decision tree to perform more<br />

sophisticated actions based on the button clicked (or use a switch construction on<br />

the btn.value expression for NN4+ and IE4+).<br />

Listing 24-1: Three Buttons Sharing One Function<br />

<br />

<br />

Button Click<br />

<br />

function displayTeam(btn) {<br />

if (btn.value == “Abbott”) {alert(“Abbott & Costello”)}<br />

if (btn.value == “Rowan”) {alert(“Rowan & Martin”)}<br />

if (btn.value == “Martin”) {alert(“Martin & Lewis”)}<br />

}<br />

<br />

<br />

<br />

Click on your favorite half of a popular comedy team:<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

document.formObject.buttonObject.onClick

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!