JavaScript Events π¶
Mentor's Note: JavaScript is "Event-Driven." It doesn't just run from top to bottom; it sits and Waits for you to do something (click, scroll, type). Itβs like a butler waiting for your command! π‘
π The Scenario: The Smart Home π ¶
Imagine you live in a high-tech smart home.
- The Event (The Trigger): You step on the Door Mat (The Action). π¦
- The Handler (The Response): The Lights Turn On π‘ automatically.
- The Connection: The house is "Listening" for your footsteps. This is exactly what an EventListener does for a website. β
π Common Web Events¶
| Category | Event Name | Trigger |
|---|---|---|
| Mouse π±οΈ | click |
User clicks an element. |
| Mouse π±οΈ | mouseover |
User hovers over an element. |
| Keyboard β¨οΈ | keydown |
User presses a key. |
| Form π | submit |
User submits a form. |
| Window π | load |
The entire page finishes loading. |
π¨ Visual Logic: The Event Cycle¶
graph TD
A[User Clicks Button π±οΈ] --> B[Browser detects Click π₯]
B --> C{Is there a listener?}
C -- Yes --> D[Run Javascript Function βοΈ]
C -- No --> E[Do nothing π€·]
D --> F[Update Website β
]
π» Implementation: The Interaction Lab¶
π Sample Dry Run¶
| Step | User Action | Computer Logic | State |
|---|---|---|---|
| 1 | Moves mouse to button | Check for mouseover |
Waiting... |
| 2 | Clicks button | click detected π₯ |
Running function |
| 3 | -- | alert() called |
Message shown π€ |
π Technical Analysis¶
- Event Propagation: When you click a button inside a box, the "Click" signal travels up from the button to the box, and then to the whole page. This is called Bubbling! π«§
π― Practice Lab π§ͺ¶
Task: The Secret Message
Task: Create a button that says "Hover over me." When the user hovers (mouseover), change the text to "I see you! π". When they leave (mouseout), change it back.
Hint: Use two addEventListener calls. π‘
π‘ Interview Tip π¶
"Interviewers love asking: 'Why use addEventListener instead of onclick?' Answer: Because
addEventListenerallows you to attach multiple actions to the same event, whileonclickonly allows one!"
π‘ Pro Tip: "The DOM is your playground. Once you master events, you can make the web do anything you can imagine!" - Anonymous