2082 6

CSC329 ยท 2082 ยท 5 marks

Write an HTML script to demonstrate the onkeydown and onkeypress events.

Write an HTML script to demonstrate the onkeydown and onkeypress events. [5]

Web TechnologyChapter 2: Hyper Text Markup LanguageHTML Events

Quick answer

These are event handlers written inside HTML tags that execute JavaScript when something happens (such as pressing a key).

HTML Script to Demonstrate onkeydown and onkeypress Events

Brief Explanation

Keyboard Events are:

AttributeDescription
onkeydownFires/runs when a user is pressing a key
onkeypressFires when user presses a key
onkeyupFires when user releases a key

HTML Script

<!DOCTYPE html>
<html>
<head>
    <title>onkeydown and onkeypress Event Demo</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 40px;
        }
        input {
            padding: 8px;
            font-size: 16px;
            width: 300px;
        }
        #output {
            margin-top: 20px;
            padding: 10px;
            background-color: #f0f0f0;
            border: 1px solid #ccc;
            width: 320px;
        }
    </style>
</head>
<body>

    <h2>Keyboard Event Demo: onkeydown and onkeypress</h2>

    <p>Type something in the textbox below:</p>

    <input
        type="text"
        id="myInput"
        onkeydown="keyDownHandler(event)"
        onkeypress="keyPressHandler(event)"
        placeholder="Type here..."
    />

    <div id="output">
        <p id="keydown_msg">onkeydown: (waiting...)</p>
        <p id="keypress_msg">onkeypress: (waiting...)</p>
    </div>

    <script type="text/javascript">

        // Fires when a user is pressing a key (onkeydown)
        function keyDownHandler(event) {
            document.getElementById("keydown_msg").innerHTML =
                "onkeydown: Key pressed down = " + event.key;
        }

        // Fires when user presses a key (onkeypress)
        function keyPressHandler(event) {
            document.getElementById("keypress_msg").innerHTML =
                "onkeypress: Key pressed = " + event.key;
        }

    </script>

</body>
</html>

Output / Explanation

When the user types in the text box:

  • onkeydown fires first, as soon as the key is pushed down, and displays the key name in the output area.
  • onkeypress fires next, when the key press is registered, and also displays the key name.

Example output when user presses the key A:

onkeydown:  Key pressed down = A
onkeypress: Key pressed = A

Note: onkeypress does not fire for non-character keys (like Shift, Ctrl, Arrow keys), whereas onkeydown fires for all keys.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.