Understanding The JavaScript Event Model (part 2) - Tonight's Menu (Page 8 of 10 )
Next, let's look at a couple of examples that demonstrate the possible applications of this capability. This next example sets up a small menu containing multiple links, each link associated with a number. The user can select a specific link by pressing the appropriate number key on the keyboard.
Here's the code for Netscape Navigator:
<html>
<head>
<script language="JavaScript">
function menuSelect(e)
{
// select 1
if(e.type == 'keydown' && e.which == 49)
{
document.location.href="link1.htm"
}
// select 2
else if(e.type == 'keydown' && e.which == 50)
{
document.location.href="link2.htm"
}
// select 3
else if(e.type == 'keydown' && e.which == 51)
{
document.location.href="link3.htm"
}
// select 4
else if(e.type == 'keydown' && e.which == 52)
{
document.location.href="link4.htm"
}
}
document.onkeydown = menuSelect;
</script>
</head>
<body>
</body>
</html>
And here's the Internet Explorer equivalent:
<html>
<head>
<script language="JavaScript">
function menuSelect()
{
// select 1
if(event.type == 'keydown' && event.keyCode == 49)
{
document.location.href="link1.htm";
}
// select 2
else if(event.type == 'keydown' && event.keyCode == 50)
{
document.location.href="link2.htm";
}
// select 3
else if(event.type == 'keydown' && event.keyCode == 51)
{
document.location.href="link3.htm";
}
// select 4
else if(event.type == 'keydown' && event.keyCode == 52)
{
document.location.href="link4.htm";
}
}
document.onkeydown = menuSelect;
</script>
</head>
<body>
</body>
</html>
A quick note on something new here: in both cases, the "type" property has been used to identify the type of event generated. This makes it possible to take action selectively, on the basis of the specific type of event generated.
Next: Reducing The Crime Rate >>
More JavaScript Articles
More By Team Melonfire, (c) Melonfire