Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 48 - JavaScript Event Object

When handling events in JavaScript, an event object is automatically passed to the event handler. This object provides details about the event, such as the type of event, the target element, and additional properties like mouse coordinates or key presses.

Why is the Event Object Important?

  • Gives access to event properties (e.g., mouse position, key pressed).
  • Helps prevent default behavior (e.g., stopping a form from submitting).
  • Allows event delegation, which helps manage multiple elements efficiently.

Syntax

element.addEventListener("event", function(event) {
    // Use the event object here
});
  • The event parameter (often written as e) represents the event object.
  • It contains useful properties and methods.

Example 1: Getting Event Details

document.addEventListener("click", function(event) {
    console.log("Event Type:", event.type);
    console.log("Clicked at X:", event.clientX, "Y:", event.clientY);
});
  • Logs the event type (click) and the mouse coordinates.

Example 2: Preventing Default Behavior

document.querySelector("a").addEventListener("click", function(event) {
    event.preventDefault(); // Prevents navigation
    console.log("Link clicked, but not redirected!");
});
  • Stops the default link redirection.

Example 3: Key Press Events

document.addEventListener("keydown", function(event) {
    console.log("Key Pressed:", event.key);
});
  • Logs the key that was pressed.

Try Your Hand

Steps:

  1. Create a File:

    • Name it lesson48-event-object.html.
  2. Write the Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
       <title>Lesson 48 - JavaScript Event Object</title>
    </head>
    <body>
       <button id="testButton">Click Me</button>
       <p id="output"></p>
    
       <script>
           document.getElementById("testButton").addEventListener("click", function(event) {
               document.getElementById("output").textContent =
                   "Button clicked at X: " + event.clientX + ", Y: " + event.clientY;
           });
       </script>
    </body>
    </html>
  3. Save and Open the file in a browser.

  4. Click the button to see the event details.


Experiment

  1. Modify the code to display the key pressed when typing in an input field.
  2. Use event.target to show which element was clicked.
  3. Prevent the right-click menu from appearing when you right-click.

Key Takeaways

  • The event object contains useful details about an event.
  • You can prevent default behavior (e.g., form submission, link redirection).
  • The event object is useful for mouse, keyboard, and other event interactions.