Bits & Bytes

Posts Tagged ‘div’

Responding to Keyboard Events in JavaScript

Key Events

In this post, we demonstrate how to catch and handle a keyboard event. There are three basic key events: key down, key up, and key press. The “key press” event is a bit different, since it describes a combination of a key up and a key down event and generates a character code. So, we will ignore the key press and concentrate on the key up and key down events, which use key codes rather than character codes.

The key down and key up events are triggered when a key is pushed in and when a key is released. During the event, a key code is generated that determines which key on the keyboard is pushed or released.

Key Codes Versus Character Codes

A key code is different than a character code because the same key can generate multiple different characters. For example, one key generates both of the characters ‘1’ and ‘!’ on the keyboard. So, ‘1’ and ‘!’ have different character codes, but they are generated by the same key and correspond to the same key code. For a full list of the JavaScript key codes, consult our table of key codes.

The JavaScript Code

Below, we have a code sample that can be copied, pasted, and saved into a simple text file that should be saved with a .html extension. Then you can double-click the file, say “KeyEvent.html”, to open it with your default browser.

In the code, the Initialize() function sets the function KeyHandler() as the event handler for key down events, and it also initializes the color of the background rectangle in the div element, myrect, to medium gray. Once the KeyHandler() function is set as the handler for key down events, it is called whenever a key is pushed while the document has focus; focus is given to whatever is currently selected to receive messages, usually the window or the control that was last clicked.

Inside of the KeyHandler() function, we have iKeyDown, which will be used to hold the key code of the key that was pushed, and we have the key codes for the left arrow and right arrow keys stored in iLeftArrow and iRightArrow, respectively. The first “if” statement is used to store the key code; the method varies depending on the browser (the else branch is for IE). The second “if” statement sets the background color to red if the left arrow is pressed, blue if the right arrow is pressed, and green if any other key is pressed.

The Code in Action

To see the code running, left-click the red rectangle above to open a new window with the code running in it; press the arrow keys to see the color change. If the color does not change, then it is because the document does not have focus. I have added a border (not used in the code below) to the rectangle that is displayed when it receives focus. To see the focus change, left-click the address in the address bar of your browser and then left-click the rectangle.



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title>XoaX.net's Javascript Keyboard Event Example</title>

<script type="text/javascript">
/*<![CDATA[*/
var qpRect = null;

function KeyHandler(qKeyEvent) {
    var iKeyDown = 0;
    var iLeftArrow = 37;
    var iRightArrow = 39;

    if (qKeyEvent) {
        iKeyDown = qKeyEvent.which;
    } else {
        iKeyDown = window.event.keyCode;
    }

    if (iKeyDown === iLeftArrow) {
        qpRect.style.backgroundColor = '#ff0000';
    } else if (iKeyDown === iRightArrow) {
        qpRect.style.backgroundColor = '#0000ff';
    } else {
        qpRect.style.backgroundColor = '#00ff00';
    }
    return false;
}

function Initialize() {
    document.onkeydown = KeyHandler;
    qpRect = document.getElementById('myrect');
    qpRect.style.backgroundColor='#888888';
}

window.onload = Initialize;
/*]]>*/
</script>
</head>

<body>

<div id="myrect" style="width: 300px; height: 200px; margin: 50px;">
</div>

</body>
</html>


Setting Colors in HTML with CSS

I have discussed how to specify a color with CSS in a prior post. Here, I will explain how the color specifications are used. To simplify the matter, I will use the hexadecimal color format for all of my color designations.

The basic block element has several distinct regions that can be specified, as I discussed in a another post on the CSS box model. Of these regions, three different colors may be selected for the border, background, and text, as shown below.

(Leviticus 10:9-11) You shall not drink wine nor any thing that may make drunk, thou nor thy sons, when you enter into the tabernacle of the testimony, lest you die: because it is an everlasting precept through your generations: And that you may have knowledge to discern between holy and unholy, between unclean and clean: And may teach the children of Israel all my ordinances which the Lord hath spoken to them by the hand of Moses.

The border is the outermost region that is colored bluish. When the border color is set, we need to specify the width and the pattern as well. In the example above, we set the border with this designation:
border:10px solid #88aacc;
To break this down, the border has a width of 10 pixels, a solid pattern, and is colored #88aacc.

Inside the border we have the background and the text. The background pinkish color is specified as
background-color:#ffddcc;
Against this background, we have a darker reddish, brown color for the text, which is specified as
color:#aa5522;
This is how the text color is set for any element.

The full specification for the div above, with all of the color and size styling, is given by this code below
<div style="width:420px; height:160px; padding:20px; border:10px solid #88aacc; background-color:#ffddcc; color:#aa5522; margin:20px;">
(Leviticus 10:9-11) You shall not drink wine nor any thing that may make drunk, thou nor thy sons, when you enter into the tabernacle of the testimony, lest you die: because it is an everlasting precept through your generations: And that you may have knowledge to discern between holy and unholy, between unclean and clean: And may teach the children of Israel all my ordinances which the Lord hath spoken to them by the hand of Moses.
</div>

Centering HTML Elements

For our first example we want to center an image like this one:
XoaX.net Logo

This image is 260×50 pixels, but we are not concerned about the height because we are talking about centering the image horizontally with respect to the containing element.

If we knew the size of the containing element, we could find the center location and position the image there. However, we often deal with elements, like the browser window, that vary a great deal. In this case, we want to keep the image centered no matter how the containing element changes.

To center the image, we enclose it within a div, where we set the width to that of the image, and the right and left margins to auto, as shown below.

<div style="width: 260px; margin-left: auto; margin-right: auto;">
<img src="XoaXLogo.png" />
</div>

For illustration, we have put the 260×50 pixel image inside of a 480×100 pixel div and colored the background gray for illustration. Notice that the image sits at the top of the gray rectangle because we have not added anything to position it vertically.