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 JavaScript 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 JavaScript.
-
You can handle events using:
β Inline event attributes (onclick,onchange, etc.)
βaddEventListener()(recommended)
