Working With Keyboard Events and Their Codes in JavaScript

Introduction

 
This article explains what keyboard events are and how you can use them to dynamically change the UI depending on the keys pressed by the user.
 

Background

 
Events are an essential part of programming since they allow the developer to rule the user interface and override the current content being displayed, to change it or to perform a task or a function inside the software application.
 
In every programming language, there are special ways of working with each of the events that are raised. JavaScript has these methods too. You can easily call the function when there is an event, programmatically or you can write the code inside the markup; with JavaScript, HTML is the markup.
 

Understanding Events

 
Events are a form of communication that takes place between a user and the application. A user clicks on a button to tell the application what to do, the application performs a task and tells the user what was done and so on. For example:
  1. <button>Click me</button>   
Once clicked it raises an event for click. You can further use this event when it is raised to work on the event relatively.
 
There are basically many types of events, mouse events, app events, system events, keyboard events, hardware and so on, and so on and so on events. But we just need to handle the events that are specially meant for us to handle, like mouse and keyboard events in our application, application's events like, IsClosing, Starting and so on.
 

Mouse Events

 
These events are triggered when the user interacts with the UI using a mouse. When a user presses the UI control such as buttons and so on, the event that is raised contains the information about the mouse button that was pressed and its code and some other related information.
 
Which you can then use to trigger some commands or perform a function. For example, when you click on a simple hyperlink:
  1. <a href="http://www.example.com">Hyperlink</a>   
What happens is, actually when it is clicked the user-agent (browser) receives this call and raises an event of the click of the hyperlink. If the application or developer has shown some interest in handling it, then the browser leaves it up to them to do whatsoever they want to do, otherwise, the browser would automatically redirect you to the location of the new document to be viewed. That is the default behavior of the browser.
 
Fr example if this is a Single Page application where you don't leave the page you're at but you get to see the new content inside the page when you click on a link. Facebook, Google+ and some other major websites use this feature to minimize the loading of their resource files and the loading of only the required data.
 

Keyboard events

 
When a user inputs a value to the system, using a keyboard, the keyboard events are triggered. As in the case of mouse details of the mouse button are attached, similarly, keyboard keyCode and other events details are attached for the keyboard event.
 
For example, when a user presses a key on the keyboard the application raises an event for the developer if the developer wants to work on that event he can. If he doesn't want to do anything he can just let the application do the default function on it. A sample input field in the HTML document is an example of this, you can allow the input to include only the numeric text and you can handle that yourself. However if you want a simple textarea that would allow all of the textual representation then you can let the application handle it itself.
 

Controls that trigger events

 
Each of the HTML elements triggers an event related to its type and function inside the document. You can handle the events that are triggered by each element as the user interacts with it. You can handle the value change event of the input field, you can handle the window closing event and many more.
 
But remember that each element only triggers the event it can perform. For example, the change event can be only triggered by an input field and not by any other element that must just contain the text like a paragraph element.
 

Handling Keyboard Events

 
JavaScript events are a very broad topic to be discussed in a single article since if discussed might lose or would need to chop down the details about the objects and their properties and events and methods to handle these events.
 
When a user presses a key, the events are triggered as discussed above. There are many events for handling the type of event that is raised, you can learn the basics about keyCode and the constant fields at the link at Mozilla Developer Network. According to Mozilla Developer Network, the following are the type of events that are raised when a user presses a key.
  1. keydown
  2. keypress
  3. keyup
These events can be handled by the developer easily and the details of these events can be access to work with these events.
 
It is also to be noted that if the key is pressed, the events repeat themself and a loop of those events start as you were to use while loop with infinite loop setting until the user lifts his finger from the button.
 

Capturing key events

 
You can capture the events using JavaScript. Either using the HTML markup or by using JavaScript event listeners, the simple way of doing this is by including a simple handler inside the markup. Like the one below:
  1. <button id="myButton" onclick="handler();">Click me</button>   
You can also handle this event using the event handlers in JavaScript.
  1. // myButton is the ID of the button, upon click    
  2. myButton.addEventListener("click",     
  3.    // run this function    
  4.    function () {    
  5.        // show an alert dialog box    
  6.        alert("Button was clicked.");    
  7.    }    
  8. );   
This would run and will show a dialog box. Simple as that! If you do not want to handle it, just leave it. The application would run the default function on it.
 
Using jQuery is a simple thing to do in this scenario since you can write the following line of code to handle the event:
  1. // upon click on button    
  2. $('#myButton').click(function () {    
  3.    // alert the user.     
  4.    alert('Button was clicke');    
  5. });   
Note: jQuery is a library of JavaScript, so anything that jQuery can do JavaScript can do for sure. But what JavaScript can do, jQuery might not be able to do. So thinking jQuery would be the perfect solution for this is not a good idea. jQuery is ideal only when you're going to write a lengthy code, jQuery would help you minimize the code to write.
 

Handling the keys

 
As discussed above, the details about every event are attached so that the developer can easily go through a level of logical operations to find the exact event he is looking for. For example, you might want to handle a key event that was triggered using the Enter key and not the other ones. The event is similar, but the keyCode for the Enter key is different. This way you can distinguish between the keys.
 
For the mouse keys, the same thing applies. You can distinguish between the right button and the left button. In fact, JavaScript attaches the details if there is the middle key on the mouse and that was clicked too. Pretty neat and simple.
 

Keyboard key handling

 
When a user presses a key, for example, Enter key, the key down, key press event triggers, it is not necessary for you to handle all of these events, you can just handle any one of these, that you are interested in handling. After this, you can call the function you want to trigger and move on.
 
Each key has a unique keyCode defined for the user to use and perform an action related to it. The Esc key, Enter key, Backspace key and so on are all alike in their structure over the system, they're keys but they differ in their codes. The code for the Enter key is 13. Since it is a commonly used key, I remember it. Remaining, you can find using the sample I have included in this project. All of the keys trigger the same function. You can find the function inside the Default.js file. It is declared as:
  1. // upon keydown on the website    
  2. $('body').keydown(function () {    
  3.     // change the value inside the element with the keyCode for this event    
  4.     $('#result').text(event.keyCode);    
  5. });   
Yes, I have used jQuery, because I wanted the code to be shorter. JavaScript would have done this too. It would work for all of the buttons on the keyboard, but the only thing different would be the properties of the button that were clicked. Each button's unique code would be displayed on the screen.
 
You can in fact add a condition, to the event to be only triggered if the button is the one you want to be handled only. For example, if the user presses Enter, you can call the function to save the message. Just as how Facebook handles the comments and chat messages.
  1. // upon keydown on the website    
  2. $('body').keydown(function () {    
  3.     // if enter key was pressed; enter button's key code is 13    
  4.     if(event.keyCode == 13) {    
  5.         // handle the action    
  6.     }    
  7. });   
This would only be triggered for the Enter key, the remaining keys would be handled by the application by itself. This is also an example of Single Page applications, where you simply handle the form submission yourself without having to POSTBACK the data from/to the server and so on. Upon an Enter key press you call a function to save the data and change the UI.
 

Application response for entering key event

 
In the application attached to this article, the application, however, interacts with all of the keys that are pressed and returns their keyCode, somehow the following is the visual of the keyCode displayed when the Enter key is pressed.
 
detect keys pressed
 
There are keyCodes for all of the buttons. You can try the sample out.
 
Points of Interest
 
Even the Window keyCode is shown and captured, but you cannot call the prevent method on it. It is a system key and must execute.


Similar Articles