Summary of “Events in JavaScript”, part 1
Events notify us that something has happened on the page, for example a button click or key press.
Adding Event Handlers
button.addEventListener('click', function () {
// Instructions
});
In the example:
buttonholds an element where we want to “listen” for an event.addEventListener()is a method that is used to add an event handler to the element.'click'is the predefined name of the click event and the first argument to theaddEventListenermethod. You can review the list of event names here.- The second argument to
addEventListeneris the handler function. The instructions are written in its body and executed only when an event occurs.
Please note that we are passing the function. We are not calling it. If we call a function, the code from this function is executed immediately, and its return value is passed instead of the function. But what we need is for the code to be executed asynchronously in response to a later click, rather than while registering the handler.
// This is the wrong way of adding a handler.
button.addEventListener('click', function () {
console.log('Button click');
}());
// The message is output to the console immediately.
// The following is the correct code.
button.addEventListener('click', function () {
console.log('Button click');
});
// The message is output when a click event is triggered.
In the example above, we pass a function that does not have its own name as the handler. In this example it is not assigned to a variable. We created it where we passed it as an argument. Functions that have no name after the function keyword are called anonymous functions.
The event Object
The event object is passed as an argument to the handler function. It is always passed by the browser to this function at the time the event occurs. This object contains many useful properties and methods.
In order to use the event, all that we need to do is give the handler function a parameter through which to access this object and write instructions. JavaScript will do the rest. It has become a standard practice among some developers to refer to this parameter using its abbreviation (evt) in order to avoid certain errors.
Default Actions
Certain page elements have default actions. For example, when you click on the submit button of a form, the data entered in this form will be sent to the server, and when you click on a link, the browser goes to that link.
The event object contains a method that cancels the event’s default action: preventDefault().
link.addEventListener('click', function(evt) {
// We cancel the default action.
evt.preventDefault();
// We add instructions for the click action.
console.log('A click occurred');
});
Keyboard Events
The “keystroke” event has a special name: 'keydown'. This event is triggered when the user presses any key. It is important to note that the event is sent to the focused element: an input field, a button, or an element with the tabindex attribute. We can listen on document to handle these keyboard events from within the page.
If we want to catch the keypress for a particular key, we can refer to the keyCode property of the event object. The property contains the code of the pressed key. For example, Enter has the code 13, whereas ESC has the code 27. We use 27 to identify ESC in this example. You can read more about these key codes here.
document.addEventListener('keydown', function(evt) {
// We check that the key code is 27
if (evt.keyCode === 27) {
// The code here is only executed when the user presses ESC
}
});
There are other properties besides keyCode for determining the pressed key. For example, key and code. The key property returns the key’s value, taking the keyboard layout into account; code identifies the physical key independently of the layout. These properties are alternatives to the deprecated keyCode property. Choose the one that provides the information your program needs, and check support in your target browsers.
Continue