Events in JavaScript are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. They are a core part of interactive web applications, allowing developers to execute code in response to user actions like clicks, form submissions, key presses, mouse movements, and more. Additionally, events can represent other things that have happened, such as the completion of asynchronous tasks, updates to the state of the web page, or system notifications.
Types of Events
JavaScript supports a wide range of events, including but not limited to:
- Mouse Events: Such as
click
,dblclick
(double click),mousedown
,mouseup
,mousemove
,mouseover
,mouseout
. - Keyboard Events: Such as
keydown
,keyup
,keypress
. - Form Events: Such as
submit
,change
,focus
,blur
. - Window Events: Such as
load
,resize
,scroll
,unload
. - Touch Events: Such as
touchstart
,touchmove
,touchend
,touchcancel
, especially useful for mobile web applications. - Drag and Drop Events: Such as
dragstart
,drag
,dragover
,drop
,dragleave
.
Listening for Events
To respond to events, you must first register an event listener. An event listener is a function that waits for a specific event to occur and executes some code in response. There are several ways to set up event listeners in JavaScript:
Using HTML Attributes
<button onclick="alert('Button clicked!')">Click Me</button>
Using the DOM Element's Properties
const button = document.querySelector('button');
button.onclick = function() {
alert('Button clicked!');
};
Using addEventListener()
const button = document.querySelector('button');
button.addEventListener('click', function() {
alert('Button clicked!');
});
addEventListener()
is the recommended way to register an event listener due to its flexibility, such as allowing multiple listeners for the same event on a single element and providing options for event capturing and once-only handling.
Event Propagation: Bubbling and Capturing
Event propagation is the order in which events are received on the DOM tree. There are two main phases: bubbling and capturing.
- Bubbling: Events start from the innermost target element and then bubble up to the outer elements. This is the default behavior.
- Capturing: Events start from the outermost element and move toward the innermost target element.
You can specify the phase when using addEventListener()
by setting the third argument to true
for capturing or false
/omitted for bubbling.
Preventing Default Behavior
Some events trigger browser actions. For example, clicking a submit button in a form submits the form. You can prevent the browser's default action using the preventDefault()
method on the event object:
const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
event.preventDefault();
// Custom form handling code
});