Click here to Skip to main content
15,881,687 members
Articles / Web Development / HTML
Tip/Trick

Working with Keyboard Events and their Codes in JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (12 votes)
14 Sep 2014CPOL8 min read 28.9K   104   14   11
How to use the keyboard events of the user and use them to dynamically change the User Interface or to perform some actions

Introduction

This article explains what keyboard events are, 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 get 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 way of communication that takes place between 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:

JavaScript
<button>Click me</button>

Once clicked, it would raise an event for click. You can further use this event, when it gets raised, to work on the event relatively.

There are basically many types of events, mouse events, app events, system events, keyboard events, hardware, etc. 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, etc.

Mouse Events

These events are triggered when the user interacts with the UI through a mouse. When a user presses the UI control such as buttons, etc., 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:

<a href="http://www.codeproject.com">CodeProject</a>

...what happens is, actually when clicked the User-agent (Browser) receives this call, and raises an event for click on the hyperlink, if the application or developer seems to show some interest in handling it, then the Browser leaves it upto them to do whatsoever they want to do, otherwise Browser would automatically redirect you to the location of the new document to be viewed. That is the default behaviour by the browser.

Example of this would be the Single Page Applications, 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 loading 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 were 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 he is in 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, 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 element 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 it is to be remembered that each element only triggers the event it can perform. For example, the change event can only be triggered by an input field, and not by any other element that has to 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 as if discussed might lose or would have 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, events are triggered as discussed above. There are many events for handling the type of event that got raised, you can learn the basics about keyCode and the constant fields in the link at Mozilla Developer Network. According to Mozilla Developer Network, the following are the type of the events that get 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 accessed to work with these events.

It is also to be noted that if the key is pressed, the events repeat themselves 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:

HTML
<button id="myButton" onclick="handler();">Click me</button>

You can also handle this event using the event handlers in JavaScript.

JavaScript
// myButton is the ID of the button, upon click
myButton.addEventListener("click", 
   // run this function
   function () {
       // show an alert dialog box
       alert("Button was clicked.");
   }
);

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, as you can write this line of code to handle the event,

JavaScript
// upon click on button
$('#myButton').click(function () {
   // alert the user. 
   alert('Button was clicked');
});

Note: jQuery is a library of JavaScript, so anything that jQuery can do, JavaScript can do for sure. But the stuff 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 Enter key and not the other ones. The event is similar, but the keyCode for the enter 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 keydown, keypress 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. Esc key, Enter key, Backspace key, etc are all alike in their structure over the system, they're keys but they differ in their codes. The code for Enter key is 13, as it is the mostly 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:

JavaScript
// upon keydown on the website
$('body').keydown(function () {
    // change the value inside the element with the keyCode for this event
    $('#result').text(event.keyCode);
});

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 was 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 the way Facebook handles the comments and chat messages.

JavaScript
// upon keydown on the website
$('body').keydown(function () {
    // if enter key was pressed; enter button's key code is 13
    if(event.keyCode == 13) {
        // handle the action
    }
});

This would only trigger for the enter key, remaining keys would be handled by the application by itself. This is also an example for the 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 ENTER key press, you call a function to save the data and change the UI.

Application Response for Enter Key Event

In the application that is attached with 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.

Enter key 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.

History

  • 15th September, 2014: First post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Pakistan Pakistan
Afzaal Ahmad Zeeshan is a computer programmer from Rabwah, Pakistan, currently living in The Netherlands, likes .NET Core and Node.js for regular everyday development. Afzaal Ahmad works at Adyen as a Developer Advocate.

He is an expert with Cloud, Mobile, and API development. Afzaal has experience with the Azure platform and likes to build cross-platform libraries/software with .NET Core. Afzaal is an Alibaba Cloud MVP, twice he has been awarded Microsoft MVP status for his community leadership in software development, four times CodeProject MVP status for technical writing and mentoring, and 4 times C# Corner MVP status in the same field.

Comments and Discussions

 
QuestionMore a Tip ... Pin
Richard MacCutchan28-Dec-14 23:26
mveRichard MacCutchan28-Dec-14 23:26 
AnswerRe: More a Tip ... Pin
OriginalGriff29-Dec-14 3:53
mveOriginalGriff29-Dec-14 3:53 
AnswerRe: More a Tip ... Pin
Afzaal Ahmad Zeeshan29-Dec-14 4:01
professionalAfzaal Ahmad Zeeshan29-Dec-14 4:01 
GeneralRe: More a Tip ... Pin
Richard MacCutchan29-Dec-14 4:37
mveRichard MacCutchan29-Dec-14 4:37 
GeneralRe: More a Tip ... Pin
Afzaal Ahmad Zeeshan29-Dec-14 5:28
professionalAfzaal Ahmad Zeeshan29-Dec-14 5:28 
QuestionSample Download Required! Pin
VICK28-Dec-14 19:09
professional VICK28-Dec-14 19:09 
AnswerRe: Sample Download Required! Pin
Afzaal Ahmad Zeeshan28-Dec-14 23:13
professionalAfzaal Ahmad Zeeshan28-Dec-14 23:13 
GeneralRe: Sample Download Required! Pin
VICK29-Dec-14 0:12
professional VICK29-Dec-14 0:12 
GeneralMy vote of 1 Pin
Raghvendra2418-Sep-14 18:35
professionalRaghvendra2418-Sep-14 18:35 
AnswerRe: My vote of 1 Pin
Afzaal Ahmad Zeeshan19-Sep-14 0:05
professionalAfzaal Ahmad Zeeshan19-Sep-14 0:05 
GeneralRe: My vote of 1 Pin
Johnny J.29-Dec-14 0:28
professionalJohnny J.29-Dec-14 0:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.