Introduction to Browser Events in JavaScript
In JavaScript, events allow you to interact with a webpage by detecting user actions like clicks, key presses, scrolling, and more. The browser listens for these events and executes event handlers (functions) when they occur.
1️⃣ What is an Event?
An event is an action or occurrence detected by the browser, such as:
✔ Clicking a button (click)
✔ Pressing a key (keydown, keyup)
✔ Moving the mouse (mousemove)
✔ Scrolling the page (scroll)
✔ Submitting a form (submit)
✔ Loading a page (load)
2️⃣ Adding an Event Listener
Use addEventListener to attach an event to an element.
✅ This runs when the button is clicked.
HTML Example
3️⃣ Types of Events
✔ Mouse Events
| Event | Description |
|---|---|
click | When an element is clicked |
dblclick | When an element is double-clicked |
mousedown | When a mouse button is pressed |
mouseup | When a mouse button is released |
mousemove | When the mouse moves |
Example: Click Event
✔ Keyboard Events
| Event | Description |
|---|---|
keydown | When a key is pressed |
keyup | When a key is released |
Example: Detect Key Press
✔ Form Events
| Event | Description |
|---|---|
submit | When a form is submitted |
change | When an input value changes |
focus | When an input field is focused |
blur | When an input field loses focus |
Example: Prevent Form Submission
✔ Window Events
| Event | Description |
|---|---|
load | When the page loads |
resize | When the window is resized |
scroll | When the page is scrolled |
Example: Detect Scrolling
4️⃣ Removing an Event Listener
Use removeEventListener to stop an event from firing.
5️⃣ Event Object (event)
The event object contains details about the event, like the target element and key pressed.
✅ Shows which element was clicked.
6️⃣ Event Propagation (Bubbling & Capturing)
Events bubble up from the target element to its parent elements.
✅ Clicking child will trigger both handlers due to bubbling.
7️⃣ Prevent Default Action
Some events have default behaviors, like form submission or link navigation.
🔥 Summary
✔ Events detect user interactions.
✔ addEventListener attaches events.
✔ removeEventListener detaches events.
✔ event object provides details.
✔ Use preventDefault() to stop default actions.
🚀 Want a hands-on example? Let me know!

