π 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.
πΉ Events can be triggered by:
- π€ User actions (clicking, typing, hovering)
- π Browser actions (page load, resize, scroll)
πΉ Common Examples of Events:
- 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 clicked -
dblclickβ when double-clicked -
mouseoverβ when mouse enters an element -
mouseoutβ when mouse leaves an element
β¨ Keyboard Events
Triggered by keyboard actions.
-
keydownβ when a key is pressed -
keyupβ when a key is released
π Form Events
Triggered by form-related actions.
-
submitβ when a form is submitted -
changeβ when input value changes -
focusβ when input gets focus -
blurβ when input loses focus
π Browser / Window Events
Triggered by browser-level activities.
-
loadβ when the page finishes loading -
resizeβ when the window size changes -
scrollβ 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.
πΉ Example Explanation:
When a user clicks a button β
JavaScript executes a function β
An action is performed (show message, submit form, etc.)
Event β Handler β Action
π Ways to Handle Events in JavaScript
There are three main ways to handle events in JavaScript.
β 1. Inline Event Handling (Not Recommended)
<button onclick="alert('Clicked')">Click</button>
β Why this is NOT recommended:
Mixes HTML and JavaScript
Hard to maintain in large projects
Not scalable
Poor separation of concerns
π This method is outdated and should be avoided in modern development.
2. DOM Property Method
const button = document.querySelector("button");
button.onclick = function () {
console.log("Button clicked");
};
β Drawback:
Only one event handler can exist
New handler overrides the previous one
3. Best Method: addEventListener (Recommended)
const button = document.querySelector("button");
button.addEventListener("click", () => {
console.log("Button clicked");
});
β Why addEventListener is best:
Allows multiple event handlers
Cleaner and scalable code
Modern JavaScript standard
Works well with frameworks like React
π‘ Best Practice:
Always use addEventListener for handling events in real-world applications.
Top comments (0)