codex-lv2-may-2025

Level Navigation: 1 2 3 4 5 6 7 8 Current Level: 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

Level 9: Event Listeners

What You’ll Do

Add event listeners to your button and input using the onEvent helper function.

Instructions

💡 Code Hints

Need help with event listeners? Check out these snippets:

✅ Check

  1. Open your webpage in a browser
  2. Open Chrome DevTools (F12) and go to the Console tab
  3. Click your button - you should see a message in the console
  4. Type in your input - you should see messages in the console as you type
  5. If you don’t see messages, check that your event listeners are set up correctly

🔍 Optional: Diving Deeper - Named Functions

Instead of using anonymous functions, you can create named functions for your event handlers:

function clickHandler() {
    console.log("Button was clicked!");
    setText("output", "Hello from the button!");
}

// Use the named functions with onEvent
onEvent("my-button", "click", clickHandler);

Named functions make your code more readable and reusable, especially when you need to use the same handler for multiple elements.

🔍 Optional: Diving Deeper - Native addEventListener

You can also use the native DOM addEventListener method instead of the helper function:

function clickHandler() {
    console.log("Button was clicked!");
    setText("output", "Hello from the button!");
}

// Use native addEventListener
document.getElementById("my-button").addEventListener("click", clickHandler);

This approach gives you direct access to the native DOM API and is the standard method used in professional JavaScript development.




Level Navigation: 1 2 3 4 5 6 7 8 Current Level: 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34