HomeJavaScript Page 8 - Understanding The JavaScript Event Model (part 1)
Linking Up - JavaScript
This may be news to you, but JavaScript comes with a powerfuland flexible event model, one which provides developers with astandardized way of trapping and handling client-side events likekeystrokes and mouse clicks. This two-part article takes an in-depthlook at how this event model works, demonstrating some practical (andnot-so-practical) uses of the most common event handlers.
Finally, the onSelect and onChange handlers come in handy when dealing with selection lists and editable text fields. Consider the following example, which demonstrates them both:
<html>
<head>
</head>
<body>
<form action="submit.php" method="post">
Enter the name of your favourite superhero:
<br>
<input type="text" name="superhero" onSelect="alert('You just selected
something!')" onChange="alert('You just changed something!')"> </form>
</body>
</html>
In this case, when the contents of the text field are selected, the onSelect handler is triggered - and when the contents are changed, the onChange handler is triggered and an appropriate message displayed.
The onChange handler is frequently used with drop-down selection lists, as in the following example:
<html>
<head>
<script language="JavaScript">
function goto()
{
document.location.href =
document.forms[0].url.options[document.forms[0].url.selectedIndex].value
;
}
</script>
</head>
<body>
<form action="submit.php" method="post">
Select from the list below:
<br>
<select name="url" size="1" onChange="goto()">
<option value="http://www.melonfire.com/">Melonfire</option>
<option value="http://www.yahoo.com/">Yahoo!</option>
<option value="http://www.cnn.com/">CNN</option>
</select>
</form>
</body>
</html>
In this case, when the user makes a selection from the list, the onChange handler is triggered and the goto() function invoked. This function looks up the list to find the index of the currently-selected item, and uses the corresponding value to redirect the browser to the named URL.