Events & Event Handling in JavaScript – A Complete Beginner Guide
Source: Dev.to

What is an Event in JavaScript?
An event is an action or occurrence that happens in the browser and can be detected by JavaScript.
Events allow JavaScript to respond to user interactions and browser activities, making web pages interactive and dynamic.
Triggers
- 👤 User actions (clicking, typing, hovering)
- 🌐 Browser actions (page load, resize, scroll)
Common examples
- Clicking a button
- Pressing a keyboard key
- Hovering over an element
- Loading a web page
In simple words
Event = Something happens → JavaScript reacts
Types of Events in JavaScript
JavaScript provides many built‑in events, grouped by their purpose.
Mouse Events
Triggered by mouse interactions.
click– when an element is clickeddblclick– when double‑clickedmouseover– when mouse enters an elementmouseout– when mouse leaves an element
Keyboard Events
Triggered by keyboard actions.
keydown– when a key is pressedkeyup– when a key is released
Form Events
Triggered by form‑related actions.
submit– when a form is submittedchange– when input value changesfocus– when input gets focusblur– when input loses focus
Browser / Window Events
Triggered by browser‑level activities.
load– when the page finishes loadingresize– when the window size changesscroll– when the page is scrolled
What is Event Handling?
Event handling is the process of writing JavaScript code that runs when an event occurs. It defines how your application reacts to user actions.
Flow
Event → Handler → Action
Ways to Handle Events in JavaScript
There are three main ways to handle events.
1. Inline Event Handling (Not Recommended)
Click
Why it’s discouraged
- Mixes HTML and JavaScript
- Hard to maintain in large projects
- Not scalable
- Poor separation of concerns
2. DOM Property Method
const button = document.querySelector("button");
button.onclick = function () {
console.log("Button clicked");
};
Drawback
- Only one handler can exist; a new assignment overwrites the previous one.
3. addEventListener (Recommended)
const button = document.querySelector("button");
button.addEventListener("click", () => {
console.log("Button clicked");
});
Why addEventListener is best
- Allows multiple event handlers for the same event
- Cleaner and more scalable code
- Modern JavaScript standard
- Works well with frameworks like React
Best Practice
Always use
addEventListenerfor handling events in real‑world applications.