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:
<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...
keydown
keypress
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:
<button id="myButton" onclick="handler();">Click me</button>
You can also handle this event using the event handlers in JavaScript.
myButton.addEventListener("click",
function () {
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,
$('#myButton').click(function () {
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:
$('body').keydown(function () {
$('#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.
$('body').keydown(function () {
if(event.keyCode == 13) {
}
});
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.
There are keyCode
s 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