When we create a website, we don't want it to only show information. We also want the website to respond when the user does something.
For example:
- Clicking a button
- Typing something in a text box
- Moving the mouse
- Pressing a keyboard key
- Submitting a form
- Loading a web page
All these actions are called events in JavaScript.
What is an Event?
An event is an action that happens in a web browser and can be detected by JavaScript.
For example, suppose we have a button:
<button id="btn">Click Me</button>
When the user clicks this button, a click event occurs.
JavaScript can listen for this event and perform an action.
const button = document.getElementById("btn");
button.addEventListener("click", function() {
console.log("Button was clicked!");
});
Here:
-
click→ Event -
addEventListener()→ Used to listen for the event -
function()→ Runs when the event happens
So, events help JavaScript understand what is happening on the web page.
Why Do We Need Events?
Events are mainly used to make a website interactive.
For example, when we click a button, we can:
- Display a message
- Change the text
- Change the color
- Open or close a menu
- Show or hide an element
- Validate a form
- Send data to a server
- Add or remove HTML elements
For example:
const button = document.getElementById("btn");
button.addEventListener("click", function() {
document.body.style.backgroundColor = "lightblue";
});
Now, whenever the user clicks the button, the background color of the page changes.
Common JavaScript Events
JavaScript provides many different events. Some commonly used events are:
| Event | When it occurs |
|---|---|
click |
When the user clicks an element |
dblclick |
When the user double-clicks an element |
mouseover |
When the mouse moves over an element |
mouseout |
When the mouse leaves an element |
mousedown |
When a mouse button is pressed |
mouseup |
When a mouse button is released |
mousemove |
When the mouse pointer moves |
keydown |
When a keyboard key is pressed |
keyup |
When a keyboard key is released |
input |
When the value of an input changes |
change |
When the value of an input or select element changes |
submit |
When a form is submitted |
focus |
When an element gets focus |
blur |
When an element loses focus |
load |
When a page or resource finishes loading |
Conclusion
Events are an important part of JavaScript because they allow web pages to respond to user actions. Actions like clicking, typing, moving the mouse, and submitting forms can all generate events.
By using addEventListener(), we can listen for these events and execute JavaScript code when they occur.
Understanding events is an important step for beginners because interactive features such as buttons, forms, menus, popups, and search boxes commonly depend on JavaScript events.
Top comments (0)