Events
Websites become interactive when they respond to user actions. Clicking a button, typing in a field, or moving the mouse are all examples of user actions.
In JavaScript, these actions are called events. Events allow your code to react to what users do on a page.
What Is an Event?
An event is something that happens in the browser, triggered by the user or the browser itself.
JavaScript listens for these events and executes code when they occur.
Common Types of Events
- Click events
- Keyboard events
- Mouse events
- Form events
- Page load events
Different events are used for different interactions.
Handling a Click Event
The most common event is a click. You can respond to it using an event listener.
let button = document.getElementById("clickBtn");
button.addEventListener("click", function () {
console.log("Button clicked");
});
This code runs every time the button is clicked.
Why Use addEventListener()?
Using addEventListener() keeps JavaScript
separate from HTML and allows multiple handlers.
It is the recommended way to handle events.
Keyboard Events
Keyboard events trigger when a user presses or releases a key.
document.addEventListener("keydown", function () {
console.log("Key pressed");
});
This is commonly used for shortcuts and validations.
Real-World Example
Imagine showing a message when a user clicks a button:
let alertBtn = document.getElementById("alertBtn");
alertBtn.addEventListener("click", function () {
alert("Action successful");
});
Events make user interfaces responsive and dynamic.
Common Beginner Mistakes
- Using inline event handlers in HTML
- Forgetting to select the element correctly
- Adding event listeners multiple times
Always keep event handling organized and clean.
Thumb Rules
- Use
addEventListener()for event handling - Keep event logic simple
- Remove listeners if they are no longer needed
- Test events across browsers
What Comes Next?
Now that you can respond to user actions, the next step is understanding how events flow through the page.
In the next lesson, we will learn about event bubbling.