Lesson 4.8: Event Handling (click, hover, input, etc.)
Event Handling in JavaScript allows web pages to respond to user actions such as clicks, typing, hovering, scrolling, or form submissions. Events make websites interactive.
1. What is an Event?
An event is an action that occurs in the browser, like:
-
Clicking a button
-
Moving the mouse
-
Typing in a textbox
-
Submitting a form
JavaScript can listen to these events and execute a function when they occur.
2. Adding Event Listeners
a) Inline Event Handling (Not Recommended)
b) Using addEventListener (Recommended)
3. Common Events
| Event Type | Example Usage |
|---|---|
click |
Detect button clicks |
mouseover |
Detect mouse hover over element |
mouseout |
Detect mouse leaving an element |
keydown |
Detect key pressed on keyboard |
keyup |
Detect key released |
input |
Detect changes in input fields |
submit |
Form submission |
load |
Detect when page or image finishes loading |
scroll |
Detect scrolling of page or element |
4. Example: Click Event
5. Example: Input Event
6. Hover Event
✅ Summary:
-
Events allow interactive web experiences.
-
Use
addEventListenerto attach functions to events. -
Common events include:
click,mouseover,input,submit,scroll, and more. -
Proper event handling improves usability and engagement.
