Event

An event is an action or occurrence that happens in the browser, such as a user clicking a button, pressing a key, or the page finishing loading. JavaScript can listen for and respond to these events.

Common Event Types

Mouse Events

  • click, dblclick, mousedown, mouseup, mousemove

Keyboard Events

  • keydown, keyup, keypress

Form Events

  • submit, change, input, focus, blur

Window Events

  • load, resize, scroll

Event Listeners

javascript
// Adding an event listener
button.addEventListener('click', (event) => {
  console.log('Button clicked!')
})

// React event handling
<button onClick={handleClick}>
  Click me
</button>

Event Object

Contains information about the event:

  • event.target - Element that triggered the event
  • event.preventDefault() - Prevent default behavior
  • event.stopPropagation() - Stop event bubbling

Event Delegation

javascript
// Handle clicks on multiple elements efficiently
document.querySelector('.list').addEventListener('click', (e) => {
  if (e.target.matches('.item')) {
    console.log('Item clicked:', e.target.textContent)
  }
})