Event Handling in JavaScript
This article explains event handling in JavaScript.
YouTube Video
javascript-html-event.html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>JavaScript & HTML</title>
6 <style>
7 * {
8 box-sizing: border-box;
9 }
10
11 body {
12 margin: 0;
13 padding: 1em;
14 padding-bottom: 10em;
15 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
16 background-color: #f7f9fc;
17 color: #333;
18 line-height: 1.6;
19 }
20
21 .container {
22 max-width: 800px;
23 margin: 0 auto;
24 padding: 1em;
25 background-color: #ffffff;
26 border: 1px solid #ccc;
27 border-radius: 10px;
28 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
29 }
30
31 .container-flex {
32 display: flex;
33 flex-wrap: wrap;
34 gap: 2em;
35 max-width: 1000px;
36 margin: 0 auto;
37 padding: 1em;
38 background-color: #ffffff;
39 border: 1px solid #ccc;
40 border-radius: 10px;
41 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
42 }
43
44 .left-column, .right-column {
45 flex: 1 1 200px;
46 min-width: 200px;
47 }
48
49 h1, h2 {
50 font-size: 1.2rem;
51 color: #007bff;
52 margin-top: 0.5em;
53 margin-bottom: 0.5em;
54 border-left: 5px solid #007bff;
55 padding-left: 0.6em;
56 background-color: #e9f2ff;
57 }
58
59 button {
60 display: block;
61 margin: 1em auto;
62 padding: 0.75em 1.5em;
63 font-size: 1rem;
64 background-color: #007bff;
65 color: white;
66 border: none;
67 border-radius: 6px;
68 cursor: pointer;
69 transition: background-color 0.3s ease;
70 }
71
72 button:hover {
73 background-color: #0056b3;
74 }
75
76 #output {
77 margin-top: 1em;
78 background-color: #1e1e1e;
79 color: #0f0;
80 padding: 1em;
81 border-radius: 8px;
82 min-height: 200px;
83 font-family: Consolas, monospace;
84 font-size: 0.95rem;
85 overflow-y: auto;
86 white-space: pre-wrap;
87 }
88
89 .highlight {
90 outline: 3px solid #ffc107; /* yellow border */
91 background-color: #fff8e1; /* soft yellow background */
92 transition: background-color 0.3s ease, outline 0.3s ease;
93 }
94
95 .active {
96 background-color: #28a745; /* green background */
97 color: #fff;
98 box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
99 transition: background-color 0.3s ease, box-shadow 0.3s ease;
100 }
101 </style>
102</head>
103<body>
104 <div class="container-flex">
105 <div class="left-column">
106 <h2>HTML Sample</h2>
107 <div id="parentDiv">
108 <button id="myButton">Click me</button>
109 </div>
110 </div>
111
112 <div class="right-column">
113 <h2>Form Sample</h2>
114 <form id="myForm">
115 <input type="text" name="username">
116 <button type="submit">Submit</button>
117 </form>
118 </div>
119 </div>
120
121 <div class="container">
122 <h1>JavaScript Console</h1>
123 <button id="executeBtn">Execute</button>
124 <div id="output"></div>
125 </div>
126
127 <script>
128 // Override console.log to display messages in the #output element
129 (function () {
130 const originalLog = console.log;
131 console.log = function (...args) {
132 originalLog.apply(console, args);
133 const output = document.getElementById('output');
134 output.textContent += args.map(String).join(' ') + '\n';
135 };
136 })();
137
138 document.getElementById('executeBtn').addEventListener('click', () => {
139 // Prevent multiple loads
140 if (document.getElementById('externalScript')) return;
141
142 const script = document.createElement('script');
143 script.src = 'javascript-html-event.js';
144 script.id = 'externalScript';
145 //script.onload = () => console.log('javascript-html-event.js loaded and executed.');
146 //script.onerror = () => console.log('Failed to load javascript-html-event.js.');
147 document.body.appendChild(script);
148 });
149 </script>
150</body>
151</html>
Event Handling in JavaScript
Event handling in JavaScript is a mechanism to execute specific actions in response to user operations (such as clicks and keyboard inputs) or browser actions. By setting up event listeners, you can create dynamic and interactive web pages.
Basics of Events
Events occur in response to user operations and browser actions. When an event occurs, the associated event handler (function) is executed. For example, there are events like the following:.
- Click (
click
) - Keyboard Input (
keydown
,keyup
) - Mouse Movement (
mousemove
,mouseover
) - Form Submission (
submit
) - Page Load Complete (
DOMContentLoaded
) - Scroll (
scroll
)
Adding Event Listeners
Event listeners are set up using the addEventListener()
method. This method calls a specific function when the specified event occurs.
Basic Syntax of addEventListener()
1element.addEventListener(event, handler);
element
is the HTML element that monitors the event.event
is the event name (for example,click
).handler
is the function that is executed when the event occurs.
Event Object
When an event occurs, JavaScript passes an event object containing the event details to the event handler. This object includes information such as which element triggered the event and which key was pressed.
Example: Using the Event Object
1<button id="myButton">Click me</button>
1const button = document.getElementById('myButton');
2
3button.addEventListener('click', (event) => {
4 console.log(event); // Display event details in the console
5 console.log('Clicked element:', event.target); // Display the clicked element
6});
- This code uses the event object to display detailed information and the clicked element in the console when the button is clicked.
Typical Events
Click Event
The click
event occurs when the user clicks on an element.
1element.addEventListener('click', () => {
2 console.log('Clicked');
3});
- This code displays a message in the console when the element is clicked.
Keyboard Events
keydown
and keyup
events occur when the user presses or releases a key. You can use event.key
to see which key was pressed.
1document.addEventListener('keydown', (event) => {
2 console.log(`Key pressed: ${event.key}`);
3});
- This code displays the name of the key in the console when the user presses a key.
Mouse Events
mousemove
and mouseover
events occur on mouse movement and hover.
1document.addEventListener('mousemove', (event) => {
2 console.log(`Mouse position: X=${event.clientX}, Y=${event.clientY}`);
3});
- This code displays the position (X and Y coordinates) in the console every time the mouse moves.
Form Events
Form-related events include submit
and input
. The submit
event occurs when a form is submitted and usually causes a page reload, but event.preventDefault()
is often used to prevent this.
Example: Preventing page reload on form submission
1<form id="myForm">
2 <input type="text" name="username">
3 <button type="submit">Submit</button>
4</form>
1const form = document.getElementById('myForm');
2
3form.addEventListener('submit', (event) => {
4 event.preventDefault(); // Prevent page reload
5 console.log('Form has been submitted');
6});
- This code prevents the page from reloading when the form is submitted and displays a message in the console instead.
Event Propagation (Bubbling and Capturing)
Events propagate through two stages: the capturing phase, which travels from the parent elements to the child elements, and the bubbling phase, which travels from the child elements to the parent elements.
Event Bubbling
By default, events occur at the innermost element and propagate outward. This is called bubbling.
Example: Bubbling Example
1<div id="parentDiv">
2 <button id="myButton">Click me</button>
3</div>
1const parent = document.getElementById('parentDiv');
2const button = document.getElementById('myButton');
3
4parent.addEventListener('click', () => {
5 console.log('Parent element was clicked');
6});
7
8button.addEventListener('click', () => {
9 console.log('Button was clicked');
10});
- In this example, when you click a button, the button's event occurs first, followed by the parent element's event.
Event Capturing
By specifying true
as the third argument in addEventListener()
, you can handle events in the capturing phase.
1parent.addEventListener('click', () => {
2 console.log('Capturing: Parent element was clicked');
3}, true);
- This code handles the parent element's click event in the capturing phase and displays a message in the console.
Preventing Propagation with stopPropagation()
You can stop events from propagating using event.stopPropagation()
.
1button.addEventListener('click', (event) => {
2 event.stopPropagation(); // Stop the event propagation
3 console.log('Button was clicked (no propagation)');
4});
- This code prevents the event from propagating when the button is clicked and displays a message in the console.
Removing Events
You can remove event listeners using removeEventListener()
. To remove an event listener, you need a reference to the function specified in addEventListener()
.
1function handleClick() {
2 console.log('Clicked');
3}
4
5const button = document.getElementById('myButton');
6button.addEventListener('click', handleClick);
7button.removeEventListener('click', handleClick); // Remove the event listener
- This code removes the click event listener from the button so that it will no longer be handled when clicked.
Custom Events
In JavaScript, you can create and trigger custom events in addition to standard events. Use the CustomEvent
constructor.
1document.addEventListener('myCustomEvent', (event) => {
2 console.log(event.detail.message); // Displays "Hello!"
3});
4
5const event = new CustomEvent('myCustomEvent', {
6 detail: {
7 message: 'Hello!'
8 }
9});
10document.dispatchEvent(event);
- This code creates and dispatches a custom event
myCustomEvent
, and displays its details in the console.
Summary
Event handling is an essential element for enhancing the interactivity of web applications. By utilizing the components of event handling, you can provide a more flexible and sophisticated user experience.
- Event Listener: Use
addEventListener()
to set an event handler on an element. - Event Object: When an event occurs, an event object is passed which can be used to obtain detailed information.
- Event Propagation: Events propagate in two phases: bubbling and capturing.
- Form Events and Custom Events: You can handle form submissions and your own custom events.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.