JavaScript Events
About JavaScript Events
In JavaScript, events are actions or occurrences that happen in the browser, which can be detected and handled by JavaScript code. Events are a core part of making web pages interactive.
Events can be triggered by user interactions, such as clicking a button, submitting a form, or moving the mouse, as well as by other actions like loading a page or resizing the window.
Why Use Events?
Events allow your website or app to respond to user actions, making it interactive, dynamic and responsive to input.
Basic Event Types
| Event | Description |
|---|---|
| click | Fires when an element is clicked |
| dblclick | Fires when an element is double-clicked |
| mouseover | Fires when the mouse pointer enters an element |
| mouseout | Fires when the mouse pointer leaves an element |
| mousedown | Fires when a mouse button is pressed down |
| mouseup | Fires when a mouse button is released |
| mousemove | Fires when the mouse pointer moves |
| keydown | Fires when a key is pressed down |
| keyup | Fires when a key is released |
| change | Fires when the value of an input changes |
| input | Fires when the value of an input changes (on every keystroke) |
| submit | Fires when a form is submitted |
| load | Fires when the whole page or an image is loaded |
| resize | Fires when the window is resized |
How to Handle JavaScript Events
There are several ways to handle JavaScript events. Here are the primary ways to handle JS events:
- Inline Event Handlers (HTML Attributes)
- DOM Property Event Handlers
- addEventListener() Method (Recommended)
Inline Event Handlers (HTML Attributes)
You attach the event handler directly to an HTML element using an on attribute (e.g., onclick, onmouseover).
This is the oldest and generally least recommended method due to its mixing of HTML and JavaScript, which can make code harder to maintain and read.
Demonstration of Above Example
When you click the button below, an alert will pop up with the message "You have clicked the button!"
Explanation of the Code
-
onclick="alert('You have clicked the button!')": This is an inline event handler that triggers an alert when the button is clicked. Here,onclickis the event attribute, and the valuealert('You have clicked the button!')is the JavaScript code that will be executed when the event occurs. In this case, it will display an alert with the message "You have clicked the button!"
DOM Property Event Handlers
You attach the event handler directly to an HTML element using an on property (e.g., onclick, onmouseover).
This method is more modern than inline event handlers and allows you to separate JavaScript from HTML, making your code easier to maintain and read.
Demonstration of Above Example
When you click the button below, an alert will pop up with the message "Button click event fired using DOM property!".
Explanation of the Code
-
const button = document.querySelector('.btnDOMProperty');: This line selects the button element with the classbtnDOMPropertyfrom the DOM. -
button.onclick = function() { ... };: This line assigns a function to theonclickproperty of the button, which will be executed when the button is clicked.
addEventListener() Method Handler
The addEventListener() method takes two arguments: the event type (like 'click') and a function to execute when that event occurs.
This is the most flexible and recommended way to handle events in modern JavaScript.
The addEventListener() method allows you to attach multiple event handlers to a single element for the same event type without overwriting previous ones.
It also provides more control over event propagation (bubbling and capturing).
Demonstration of Above Example
When you click the button below, an alert will pop up with the message "Button click event fired using addEventListener() method!".
Explanation of the Code
-
const button = document.querySelector('.btnEventListener'): This line selects the button element with the classbtnEventListenerfrom the DOM. -
button.addEventListener('click', ... };: This line attaches an event listener by usingaddEventListener()method to the button that listens for the 'click' event and executes the provided function when the event occurs.
Event Object
When an event occurs in the browser (like a click, keypress, or mouse movement), the browser creates an event object containing details about that event.
This event object is automatically passed to the event handler function as the first argument.
The event object contains properties and methods that provide information about the event, such as the type of event, the target element, and any additional data related to the event.
Common Event Object Properties
-
type: The type of event (e.g., "click", "keydown") -
target: The element that triggered the event -
currentTarget: The element the event listener is attached to -
timeStam:: When the event occurred (in milliseconds)
Common Event Object Methods
-
preventDefault(): Prevents the browser's default behavior for the event (e.g., stop form submission, prevent link navigation). -
stopPropagation(): Stops the event from bubbling up or capturing down the DOM tree (e.g., prevent parent elements from receiving the event).
Here is an example of how to use the event object properties in a click event handler:
Demonstration of Above Example
When you click the button below, an alert will pop up with the message of some event properties.
Explanation of the Code
-
button.addEventListener('click', function(event) {...})": This line attaches an event listener to the button that listens for the 'click' event and executes the provided function when the event occurs. It also passes the event object as an argument to the function and displays some properties of event object in the alert.
Here is an example of how to use the event object methods in a 'submit' event handler to prevent the default form submission behavior:
Demonstration of Above Example
When you click the button below, an alert will pop up with the message "The form was prevented from submission.".
Explanation of the Code
-
form.addEventListener('submit', function(event) {{...})": This line attaches an event listener to the form that listens for the 'submit' event and prevents the default form submission behavior by callingevent.preventDefault(). It also displays a message in the alert.
Event Bubbling and Capturing
When an event occurs, it doesn't just affect the element you clicked — it can travel through multiple elements in the DOM tree.
There are three phases of event propagation in the DOM: capturing, target, and bubbling.
3 phases in event propagation:
- Capturing Phase: The event starts from the root of the DOM tree and goes down to the target element.
- Target Phase: The event reaches the target element where it was triggered.
- Bubbling Phase: The event bubbles back up to the root of the DOM tree, triggering any event listeners attached to parent elements.
Following is an example of how propagation works:
Explanation of the propagation (When you click the button)
- Capture phase: document → html → body → #outer → #middle → #inner
- Target phase: The actual element (#inner) is clicked.
- Bubble phase: #inner → #middle → #outer → body → html → document
Here is an example of how event propagation works in JavaScript. In this example, we will create a nested structure of elements and attach event listeners to each level of the hierarchy. Whenever you click on the innermost element, the event will propagate through the DOM tree, demonstrating both capturing and bubbling phases.
Demonstration of Above Example
Try to simulate the event propagation by clicking on the "Outer DIV", "Middle BUTTON", and "Inner SPAN" and check how the events propagate through the DOM tree.
Event Delegation
Event Delegation is a technique where you don't attach event listeners to individual child elements. Instead, you attach a single event listener to a parent element and catch events that bubble up from its child elements.
This is particularly useful when you have a large number of elements or dynamically generated content, as it reduces memory usage and improves performance.
Why use Event Delegation?
- Better performance.: One event listener instead of many.
- Dynamic contents: Automatically handles new elements added dynamically.
- Cleaner code: Easier to maintain, less repetitive.
Simple Example Without Delegation
Following is a simple example of how to handle events without delegation. In this example, we will create a set of buttons that alert their text content when clicked. Each button has its own event listener. foreach loop is used to attach the event listener to each button individually.
Problems with the example:
- If you have many buttons, it can lead to performance issues due to multiple event listeners.
- If new buttons are added dynamically, they won’t work unless you add listeners again.
- Code can become repetitive and harder to maintain.
Same Example With Event Delegation
Following is a same example of how to handle events delegation. In this example, we will create a set of buttons that alert their text content when clicked. Instead of attaching an event listener to each button, we will attach a single event listener to the parent container. This way, when any button is clicked, the event bubbles up to the container, and we can handle it there.
Explanation of the event delegation
-
document.getElementById('container').addEventListener('click', function(event) {...}): This line attaches a single event listener to the parent container that listens for click events. When any button is clicked, the event bubbles up to the container. The container checks event.target to see if a button was clicked. -
if (event.target.tagName === 'BUTTON'): This condition checks if the clicked element is a button. If it is, it executes the alert with the button's text content. -
alert(event.target.textContent): This line displays an alert with the text content of the clicked button.
Another Example of Event Delegation
Following is another example of how to handle events delegation. In this example, we will create a list where clicking on any item will alert its text content. Instead of attaching an event listener to each list item, we will attach a single event listener to the parent ul element. This way, when any list item is clicked, the event bubbles up to the ul, and we can handle it there.
Explanation of the event delegation
-
const list = document.querySelector('#list ul');: This line selects theulelement where the list items will be added. -
const addButton = document.querySelector('#list button');: This line selects the button that will be used to add new items to the list. -
addButton.addEventListener('click', () => {...}): This line attaches an event listener to the button that creates a new list item and appends it to theulwhen clicked. -
list.addEventListener('click', function(event) {...}): This line attaches a single event listener to theulthat listens for click events. When any list item is clicked, the event bubbles up to theul, and we can handle it there. -
if (event.target.tagName === 'LI'): This condition checks if the clicked element is a list item. If it is, it executes the alert with the item's text content. -
alert('You clicked: ' + event.target.textContent): This line displays an alert with the text content of the clicked list item.
How Does Event Delegation Work Internally?
- When an event occurs on a child element, the event bubbles up to the parent element.
-
The parent element's event listener checks if the event target matches the desired child element. (The
event.targettells which child element originally triggered the event.) - If it matches, the parent element's event handler executes the desired action.
- If it doesn't match, the event continues to bubble up to the next parent element until it reaches the root of the DOM tree or is stopped.
Types of Events
JavaScript provides a wide range of events that can be used to interact with the user and respond to their actions. Here are some common types of events in JavaScript:
1. Mouse Events
Mouse events are triggered by mouse actions such as clicks, movements, and button presses. They are commonly used for user interactions with web elements.
| Event | Description |
|---|---|
| click | Fires when an element is clicked |
| dblclick | Fires when an element is double-clicked |
| mousedown | Fires when the mouse button is pressed |
| mouseup | Fires when the mouse button is released |
| mousemove | Fires when the mouse pointer moves |
| mouseover | Fires when the pointer enters an element |
| mouseout | Fires when the pointer leaves an element |
| mouseenter | Fires when the pointer enters an element (does not bubble) |
| mouseleave | Fires when the pointer leaves an element (does not bubble) |
| contextmenu | Fires on right-click to open context menu |
2. Keyboard Events
Keyboard events are triggered by keyboard actions such as key presses and releases. They are commonly used for form inputs and keyboard shortcuts.
| Event | Description |
|---|---|
| keydown | Fires when a key is pressed down |
| keypress | Fires when a key is pressed (deprecated) |
| keyup | Fires when a key is released |
3. Form Events
Form events are triggered by user interactions with form elements such as input fields, checkboxes, and buttons. They are commonly used for form validation and submission.
| Event | Description |
|---|---|
| submit | Fires when a form is submitted |
| change | Fires when the value of a form element changes |
| input | Fires when the value of an input changes |
| focus | Fires when an element receives focus |
| blur | Fires when an element loses focus |
| reset | Fires when a form is reset |
| invalid | Fires when a form element fails validation |
4. Focus Events
Focus events are triggered when an element gains or loses focus. They are commonly used for input validation and user interactions with form elements.
| Event | Description |
|---|---|
| focusin | Fires when an element is about to receive focus |
| focusout | Fires when an element is about to lose focus |
5. Clipboard Events
Clipboard events are triggered by actions related to the clipboard, such as copying, cutting, and pasting content. They are commonly used for text manipulation and data transfer.
| Event | Description |
|---|---|
| copy | Fires when content is copied |
| cut | Fires when content is cut |
| paste | Fires when content is pasted |
6. Drag and Drop Events
Drag and drop events are triggered by user interactions with draggable elements. They are commonly used for implementing drag-and-drop functionality in web applications.
| Event | Description |
|---|---|
| drag | Fires when an element is being dragged |
| dragstart | Fires at the start of a drag operation |
| dragend | Fires at the end of a drag operation |
| dragenter | Fires when dragged item enters drop target |
| dragover | Fires when dragged item is over drop target |
| dragleave | Fires when dragged item leaves drop target |
| drop | Fires when item is dropped on target |
7. Touch Events
Touch events are triggered by touch interactions on touch-enabled devices. They are commonly used for mobile applications and touch interfaces.
| Event | Description |
|---|---|
| touchstart | Fires when touch starts |
| touchend | Fires when touch ends |
| touchmove | Fires when finger moves over the screen |
| touchcancel | Fires when touch is interrupted |
8. Pointer Events
Pointer events are a unified way to handle input from various pointing devices, such as mouse, touch, and stylus. They provide a consistent interface for handling different types of input.
| Event | Description |
|---|---|
| pointerdown | Fires when a pointer is pressed down |
| pointerup | Fires when a pointer is released |
| pointermove | Fires when a pointer moves |
| pointerover | Fires when a pointer enters an element |
| pointerout | Fires when a pointer leaves an element |
| pointerenter | Fires when a pointer enters an element (non-bubbling) |
| pointerleave | Fires when a pointer leaves an element (non-bubbling) |
| gotpointercapture | Fires when an element receives pointer capture |
| lostpointercapture | Fires when a pointer capture is released |
| pointercancel | Fires when a pointer is canceled |
9. Window Events
Window events are triggered by actions related to the browser window, such as loading, resizing, and scrolling. They are commonly used for managing the overall behavior of the web page.
| Event | Description |
|---|---|
| load | Fires when page is fully loaded |
| beforeunload | Fires before the page unloads |
| unload | Fires when the page is unloaded |
| resize | Fires when the window is resized |
| scroll | Fires when the user scrolls the page |
| hashchange | Fires when the URL hash changes |
| popstate | Fires when the active history entry changes |
11. Animation Events
Animation events are triggered by CSS animations. They are commonly used to handle animation start, end, and iteration events.
| Event | Description |
|---|---|
| animationstart | Fires when animation starts |
| animationend | Fires when animation ends |
| animationiteration | Fires when animation repeats |
12. Transition Events
Transition events are triggered by CSS transitions. They are commonly used to handle transition start, end, and cancellation events.
| Event | Description |
|---|---|
| transitionstart | Fires when transition starts |
| transitionend | Fires when transition ends |
| transitionrun | Fires when transition is running |
| transitioncancel | Fires when transition is cancelled |
13. Miscellaneous Events
There are various other events that do not fit into the above categories. These events can be used for specific use cases and functionalities.
| Event | Description |
|---|---|
| error | Fires on script or resource loading error |
| abort | Fires when loading is aborted |
| wheel | Fires when mouse wheel is used |
| message | Fires when receiving messages (e.g. postMessage) |
| online | Fires when the browser goes online |
| offline | Fires when the browser goes offline |
HTML Editor For Live Practice
Practice the above JavaScript code in the following HTML Editor. Create different types of events in the following HTML code editor and click Render Code button to check the output. The output will be displayed in HTML Output section.
HTML Editor