Welcome to our comprehensive guide on JavaScript events reference. In this section, you'll find a wealth of information about JavaScript events, their syntax, usage, and examples. Whether you're a beginner or an experienced developer, this guide will help you understand and utilize JavaScript events effectively.
What are JavaScript Events?
JavaScript events are actions or occurrences that happen in the browser, such as clicks, mouse movements, key presses, and more. Events can be triggered by the user or by the browser itself, and they allow you to add interactivity to your web applications.
Common JavaScript Events
Here's a list of some common JavaScript events:
- Click
- Mouseover
- Mouseout
- Keydown
- Keypress
- Keyup
- Submit
- Load
Example: Click Event
Here's a simple example of a click event in action:
document.getElementById("myButton").addEventListener("click", function() {
alert("Button clicked!");
});
Event Listeners
To handle events, you need to add event listeners to the elements on your web page. Event listeners are functions that are executed when a specific event occurs.
Example: Adding an Event Listener
var button = document.getElementById("myButton");
button.addEventListener("click", function() {
alert("Button clicked!");
});
Event Objects
When an event occurs, a special object called an "event object" is passed to the event listener function. This object contains information about the event, such as its type, target, and more.
Example: Using Event Objects
document.getElementById("myButton").addEventListener("click", function(event) {
console.log("Button clicked!");
console.log(event.type); // "click"
console.log(event.target); // The button element
});
Event Bubbling and Capturing
When an event occurs, it can be handled in different phases: capturing, at the target, and bubbling. This is known as the event propagation phase.
Example: Event Propagation
document.getElementById("myContainer").addEventListener("click", function(event) {
console.log("Container clicked!");
});
document.getElementById("myButton").addEventListener("click", function(event) {
console.log("Button clicked!");
});
Handling Event Defaults
Sometimes, you may want to prevent the default behavior of an event, such as preventing a form from submitting or preventing a link from navigating to a new page.
Example: Preventing Default Behavior
document.getElementById("myLink").addEventListener("click", function(event) {
event.preventDefault();
});
For more in-depth information on JavaScript events, be sure to check out our JavaScript Basics guide.