Skip to content

Event Listener Not Firing

Quick summary

Your event listener is not firing because the element does not exist when the listener is attached, or the event name is wrong.

Why this happens

  • The element does not exist in the DOM when addEventListener is called

  • Typo in the event name (e.g., 'onclick' instead of 'click')

  • The event listener is attached to the wrong element

Minimal example

✗ Broken code
// Script in <head> — element does not exist yet
const btn = document.querySelector("#myBtn");
btn.addEventListener("click", handler); // btn is null!
✓ Fixed code
// Option 1: defer
// <script src="app.js" defer></script>

// Option 2: DOMContentLoaded
document.addEventListener("DOMContentLoaded", () => {
  const btn = document.querySelector("#myBtn");
  btn.addEventListener("click", handler);
});

If the script runs before the DOM is parsed, the element does not exist and querySelector returns null. Use defer or DOMContentLoaded to ensure the element exists.

How to diagnose

  • Add a console.log inside the handler to verify it is not being called

  • Check if the element exists before attaching the listener (console.log the element)

  • Verify the event name is correct (e.g., 'click', not 'onClick')

How to fix

  • Move the script to the end of <body> or use defer

  • Wrap the code in DOMContentLoaded event listener

  • Fix the event name typo

How to prevent

  • Use the defer attribute on scripts or place them at the end of <body>

  • Use event delegation for dynamically added elements

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language