English

Events & Interactions

🎯 Learning Goals

  • Understand how JavaScript listens for user actions
  • Learn to trigger functions in response to clicks, typing, and mouse movements

💡 Why Learn This?

A webpage that only displays information is static. Events are the bridge between the user and the application. Without events, a button cannot submit a form, and a game character cannot move when you press a key.

Listening to the User

An 'Event' is an action that happens in the browser, like a mouse click, a key press, or the window loading. JavaScript can attach 'Event Listeners' to HTML elements, which act as guards waiting for a specific event to happen before running a block of code.

btn.addEventListener(
'click',
function(event) {
// Do something
}
);

Common Event Types

  • Mouse: click, dblclick, mouseenter, mouseleave
  • Keyboard: keydown, keyup, keypress

⚠️ Common Pitfalls

A common pitfall is forgetting that some events fire hundreds of times per second (like 'mousemove' or 'scroll'). Running heavy code on these events without optimization can freeze the browser!

Interactive Simulator

Interact with the box below using your mouse and keyboard to see which events are triggered in real-time.

🎯

Interact with me! (Hover, Click, Type)

(Click to focus for keyboard events)

Event Log
Waiting for events...

📝 Summary & Recap

  • Use addEventListener() to listen for user actions without cluttering your HTML.
  • Event objects contain useful data about the action, such as which key was pressed or where the mouse was clicked.

Quick Drill

Test your knowledge of JavaScript events!

Which event fires when a user presses a key on the keyboard?

🔍 Deep Dive (Optional)

In the early days of the web, 'inline event handlers' (like onclick='doSomething()') were the only way to trigger JavaScript. This led to 'spaghetti code' where structure and logic were hopelessly mixed. The modern DOM Level 2 Events model (introduced in 2000) brought us addEventListener, finally separating logic from presentation.

Google AdSense Area