Events are actions that take place in the browser and trigger an action.
Event listeners attach a responsive interface to an element. They are a relatively new concept in JS but are more commonly used than event handlers because they have more advantages, such as:
1. You can set multiple event listeners to the same element and they will all fire when called.
2. You can apply an event listener to the document and window object.
Below we will outline how to use the .addEventListerner() and outline some common events.
To see examples of eventlisteners, head over the the 'JS examples' page or
CLICK HERE!
Event Listeners
The .addEventListener(); takes two mandatory parameters:
1. The event it is listening for.
2. The listener call-back function.
Common events:
EVENT |
DESCRIPTION |
click |
Fires when element is clicked once |
dblclick |
Fires when element is clicked twice |
mouseenter |
Fires when pointer enters element |
mouseleave |
Fires when pointer leaves element |
mousemove |
Fires everytime mouse moves in element. |
submit |
Fires when a form is submitted. |
focus |
Fires when an element receives focus on a form. |
blur |
Fires when an element loses focus on a form. |
keydown |
When a key is pressed |
keyup |
When a key is released |
keypress |
Fires continuously when a key is pressed. |
Keyboard events such as keydown, keyup and keypress can contain keyboard properties to access more information about the action:
1. keyCode - A number pertainining to a key.
2. key - Represents a character name.
3. code - Represents physical key being pressed.
Event objects:
The event object is often written as 'event' or 'e' and is passed through a listener function as a parameter, it has properties and methods that all events can access.
event.target allows you to place an event listener on an outer element and it can still access the nested elements within that element.
To see examples click on the link above.