⚡ JavaScript Events

Make your websites interactive - respond to clicks, hovers, key presses, and more!

🤔 What are Events?

Events are actions that happen in the browser - like clicking a button, moving the mouse, typing on the keyboard, or submitting a form.

Common Events:

click - User clicks an element
mouseover - Mouse enters an element
mouseout - Mouse leaves an element
keypress - User presses a key
submit - Form is submitted
change - Input value changes

🎯 addEventListener() Method

The modern way to handle events in JavaScript:

// Get the element
var button = document.getElementById("myButton");

// Add event listener
button.addEventListener("click", function() {
  console.log("Button was clicked!");
});

🎨 Click Event Demo

🖱️ Mouse Events

🎨 Mouseover and Mouseout

⌨️ Keyboard Events

Respond to key presses:

document.addEventListener("keypress", function(event) {
  console.log("Key pressed: " + event.key);
});

📋 Form Events

✅ Submit Event

var form = document.getElementById("myForm");

form.addEventListener("submit", function(event) {
  event.preventDefault(); // Stop form from submitting
  console.log("Form submitted!");
});

🎨 Live Form Validation

🎯 Event Object

The event object contains information about the event:

button.addEventListener("click", function(event) {
  console.log(event.target);    // Element that was clicked
  console.log(event.type);      // "click"
  console.log(event.clientX);   // Mouse X position
  console.log(event.clientY);   // Mouse Y position
});

✏️ Practice Exercise

Challenge: Build Interactive Features!

  1. Create a button that changes color when clicked
  2. Make a box that changes color on mouseover
  3. Build a simple typing game that counts keystrokes
  4. Create a form with real-time validation
  5. Build a color picker that changes background

🎯 Key Takeaways

📚 Class 8 - Advanced JavaScript • Make It Interactive! 🚀