HTML5 Zone is brought to you in partnership with:

Gil Fink, Microsoft MVP, is an expert in Web development and Microsoft data platform. He works as a senior architect at Sela Group. He is currently consulting for various enterprises and companies, where he architects and develops Web and RIA-based solutions. He conducts lectures and workshops for developers and enterprises who want to specialize in infrastructure and Web development. He is also a co-author of several Microsoft Official Courses and training kits. You can read his publications at his blog: http://blogs.microsoft.co.il/blogs/gilf. Gil is a DZone MVB and is not an employee of DZone and has posted 151 posts at DZone. You can read more from them at their website. View Full User Profile

Back to Basics – Using Keyboard Events in JavaScript

09.17.2012
| 8671 views |
  • submit to reddit

A few months ago I was implementing a POC for a customer and was in a need for reading keyboard presses through JavaScript. I was asked the same question today so I guess that means a post.

The Scenario

You need to read all the keyboard key presses up until the Enter key is used.
You should output the typed word without the Enter key.

Wiring The Events

In order to listen to key presses, you will wire an event listener to the keypress event. That event listen to all key presses and in its handler you will store the key pressed (but won’t store the Enter key press). Here is an example for doing that:

window.addEventListener('keypress', function (e) {
    if (e.keyCode !== 13) {
        chars.push(e.key);
    }
}, false);

In the example, you wire the keypress event. If the key press isn’t Enter (Enter key code is 13), you push the pressed key to a character array.

In order to catch the Enter key press and output the typed word, you will wire an event listener to the keyup event. That event listen to the end of key pressing (when the user stop pressing a key). Here is an example for wiring the event:

window.addEventListener('keyup', function (e) {
    if (e.keyCode === 13) {
        container.textContent = chars.join('');
        chars = [];
    }
}, false);

In the example, you wire the keyup event. If the key is released, you check whether the pressed key was Enter. If the key was Enter, you put the content of the characters array into a container div and you clear the array.

The Full Example

Here is all the code for the example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Keyboard Reading</title>

    <script type="text/javascript">
    (function () {
        function contentLoaded () {    
                var chars = [],
                container = document.getElementById('container');

                window.addEventListener('keypress', function (e) {
                if (e.keyCode !== 13) {
                            chars.push(e.key);
                }
                }, false);

                window.addEventListener('keyup', function (e) {
                    if (e.keyCode === 13) {
                        container.textContent = chars.join('');
                chars = [];
                       }
                }, false);
        }

        window.addEventListener('DOMContentLoaded', contentLoaded, false); 
    }());
    </script>
</head>
<body>
    <div id="container">
    </div>
</body>
</html>

Summary

In order to read keyboard pressed keys in JavaScript you can use events such as keypress and keyup. The example that I showed is very basic but it was the starting point for reading data sent from a barcode reader that was acting like a keyboard in the POC I mentioned.

Published at DZone with permission of Gil Fink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)