JavaScript Events
JavaScript Events
JavaScript events are actions or occurrences that happen in the browser. JavaScript can respond to these events and make the webpage interactive.
Examples of events:
-
Clicking a button
-
Typing in a text box
-
Hovering the mouse
-
Loading a web page
-
Submitting a form
📌 Common Browser Events
| Event | Description |
|---|---|
onclick |
User clicks an element |
onmouseover |
Mouse moves over an element |
onmouseout |
Mouse leaves an element |
onchange |
Content of input field changes |
onkeydown |
A key is pressed |
onload |
Page or image finishes loading |
Example 1: Click Event
Example 2: Mouse Over Event
Example 3: addEventListener() (Best Practice)
Example 4: Input Field Change Event
🎯 Why Use Events?
Events allow Js to:
✔ Create interactive pages
✔ Validate forms
✔ React to user behavior
✔ Build dynamic UI features
📌 Using addEventListener() vs Inline Events
| Feature | Inline Event | addEventListener |
|---|---|---|
| Cleaner code | ❌ No | ✔ Yes |
| Multiple handlers possible | ❌ No | ✔ Yes |
| Modern approach | ❌ Old | ✔ Recommended |
Example:
🚀 Summary
-
Events trigger actions in Js.
-
You can handle events using:
✔ Inline event attributes (onclick,onchange, etc.)
✔addEventListener()(recommended)
