In this fifth part of a six-part series on building a web page calculator, we shall see how to use the keyboard with the calculator. The event involved is the onkeypress event, which we saw in the last part of the series. For an element to respond to the event, it has to have focus. With some browsers, if all of the elements that have to respond to the keyboard have the same function, and are in the same group (on the calculator), you only have to give one of the elements focus. This is the case with my browser.
More on the Keyboard for a Web Page Calculator - The processKey(e) Function (Page 2 of 5 )
The processKey(e) function has two parts. The first part operates when you are using Internet Explorer. The second part is an alternative to the first part; it operates if you are using Netscape, Firefox or Opera. This is the skeleton of the function:
function processKey(e)
{
if(window.event) // IE
{
//key identifiers
if (/d/.test(keychar))
{
//respond to a digit press
}
else if (/./.test(keychar))
{
//respond to the decimal point press
}
else if (/+|-|*|/|=/.test(keychar))
{
//respond to an operator key press
}
else if (keynum == "13") //for the equal sign
{
//respond to the Enter key press.
}
}
if(e.which) // Netscape/Firefox/Opera
{
if(window.event) // IE
{
//key identifiers
if (/d/.test(keychar))
{
//respond to a digit press
}
else if (/./.test(keychar))
{
//respond to the decimal point press
}
else if (/+|-|*|/|=/.test(keychar))
{
//respond to an operator key press
}
else if (keynum == "13") //for the equal sign
{
//respond to the Enter key press.
}
}
}
The processKey(e) function has two parts; there are five code segment for each part. These code segments, except the first, are the same for either part. Either part of the function begins with an “if” line. It verifies the browser type. I explained this in the previous part of the series.
The first code segment has the identifiers (key code and character) for the key that have been pressed. Each of the other code segments is a block in an if-else-if statement. The second code segment responds when a digit is pressed on the keyboard. The third code segment responds when the decimal point is pressed. The fourth code segment responds when an operator key (+, -, X, or /) is pressed. The fifth code segment responds when the Enter key is pressed.