JavaScript Events

JavaScript Tutorial

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

EventDescription
onclickUser clicks an element
onmouseoverMouse moves over an element
onmouseoutMouse leaves an element
onchangeContent of input field changes
onkeydownA key is pressed
onloadPage 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

FeatureInline EventaddEventListener
Cleaner code No Yes
Multiple handlers possible NoYes
Modern approach OldRecommended

Example:

 Summary

  • Events trigger actions in Js.

  • You can handle events using:
    ✔ Inline event attributes (onclick, onchange, etc.)
    addEventListener() (recommended)

You may also like...