[FIXED] addEventListener click not working
Understanding Event Listeners in JavaScript - fixing addEventListener issues
Jun 29, 2023 | Read time 9 minutes | Updated on Feb 4, 2024đ Table of contents
Introduction
The reasons why addEventListener click not working on your website could be:
- Element does not exist at script execution
- Selector is incorrect
- Not using addEventListener correctly
- Click event is being prevented by another code
- The element is not interactive and will not accept addEventListener
- Fix other Javascript errors on the page
When I was working on a old web design, I had to do this feature where the user clicks on this button and a overlay would appear.
I have tried working with âaddEventListenerâ function but no idea why it is not working.
In the end I found that my selector is not right - I was targeting the wrong element!
In this post, I will go over my troubleshooting checklist to deal with this issue.
1. Element does not exist
One thing that could trip you up is that the element you are adding the âaddEventListenerâ function to does not exist at the time of the script execution.
Generally this happens when you have scripts that run too early (top of the HTML page) or that you have dynamic elements.
One way to get around this is to use the DOMContentLoaded
handler:
document.addEventListener('DOMContentLoaded', function() {
let button = document.querySelector('#myButton');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
});
Alternatively, you can place your <script>
at the end of the HTML page and also use the defer
attribute:
<script src="demo_defer.js" defer></script>
This ensures that it is executed AFTER the page has finished parsing!
Keep in mind that there are some things you will have to keep in mind when working with defer
scripts:
- Deferred scripts wait for stylesheets to load before executing.
DOMContentLoaded
event is queued after the execution of deferred scripts.- Scripts that are not deferred or async (e.g., using a regular
<script>
tag) wait for already-parsed stylesheets to load before executing.
2. Selector is incorrect
A common mistake is that you are not targeting the right element - Dâoh!
For example, some of my mistakes previously:
// â failed because there are multiple '.small-button' elements and querySelector only retrieves the first one
document.querySelector(".small-button").addEventListener('click', function() {
// do something
});
// â failed because querySelectorAll returns a list - and addEventLister is available for single elements
document.querySelectorAll(".small-button").addEventListener('click', function() {
// do something
});
// â failed because the hash '#' is not needed
document.getElementById("#mybutton").addEventListener('click', function() {
// do something
});
3. Not using addEventListener correctly
Another common issue is not using âaddEventListenerâ correctly.
The specifications state that the function will only work for elements that support events.
The syntax will look like this:
addEventListener(type, listener, options)
- type is a string of a âevent typeâ and case-sensitive. So this means that âClickâ (and will not work) is different to âclickâ. You can see all possible event types here: Events
- listener is a function reference.
A common way to use âaddEventListenerâ is as follows:
let button = document.querySelector('#myButton');
button.addEventListener('click', function() {
console.log('Button clicked!');
});
What can trip you up is that the âlistenerâ parameter has to be a function REFERENCE - and not function CALL
So to understand this - lets consider we have a function addTodo
and we want to be called everytime someone clicks your button.
The proper way to do this is:
.addEventListener("click", addTodo, false);
However, if you write addTodo()
- notice the extra brackets ()
:
// â failed because the addTodo() brackets
.addEventListener("click", addTodo(), false);
addTodo()
is executed immediately - and this is not the behavior we want. Since addTodo()
will execute immediately and will not trigger when someone clicks your button!
4. Click event is being prevented by another code
This might be a bit tricker to fix since it will involve you looking throughout the codebase.
Generally, you want to check if thereâs another addEventListener
thatâs preventing the propagation of the event (using event.stopPropagation() or event.stopImmediatePropagation()), then the click event may not be triggered.
5. The element is not interactive and will not accept addEventListener
The addEventListener
does not accept all HTML elements. It only accepts elements that support interactive events. For example, <span>
tags and <div>
tags donât inherently respond to click events unless they have a tabindex or explicit role attribute indicating they should be interactive.
In HTML, only certain elements are naturally interactive and can receive focus (and subsequently, certain events).
For example, anchor (<a>
), button (<button>
), and input (<input>
) elements are naturally interactive, meaning they can be focused on and clicked. They can naturally receive âclickâ events, keyboard events like âkeypressâ, âkeydownâ, âkeyupâ, etc.
Non-interactive elements like <param>
, <head>
, <title>
, <script>
, <track>
, <code>
, etc., are not naturally focusable or interactive. They do not naturally receive these same events.
6. Fix other Javascript errors on the page
If you have other JavaScript errors prior to the addEventListener
in your code, they could be stopping your script from executing further, including the part where you add the event listener.
JavaScript will stop executing code at the point where it encounters an unhandled error.
Generally, I would look at the browser console to see if theres any errors that pops up. Make sure to fix those errors first.
Somethings that tripped me up in the past includes:
- Not matching opening and closing brackets
- Incorrect variable or function names (JavaScript is case-sensitive)
- Accessing a variable that has not been defined
- Trying to access properties or methods on null or undefined - could be result of failed CORS or AJAX calls.
Keep in mind that the order of the scripts in your HTML file matters.
Make sure that any dependencies (like libraries or other custom scripts) are loaded before your script.
Also, ensure your DOM elements are loaded before trying to access them by running your code inside a DOMContentLoaded event handler, or by placing your script tags right before the closing tag.
Browser compatibility
-
IE<=8 instead only supports the proprietary .attachEvent() method. It also does not support the capture phase of DOM event dispatch; it only supports event bubbling.
-
The useCapture parameter is non-optional and must be provided. Future versions made it optional, with a default value of false.
Tips for using addEventListener
- When you are using anonymous functions to as handlers, keep in mind of memory issues. Repeatedly assigning a anonymous function to the same element will cause memory to blow out since Javascript will treat these functions differently.
- Make sure you also use the âremoveEventListenerâ where possible. This way we do not have so many handlers hanging around and slowing down your app.
- addEventListener is the recommended way to handle events for HTML elements due to its wide support and ability to remove handlers when not needed. Other options include the âonclickâ handlers, but not generally recommended!
Summary
In this post we went over the reasons why addEventListener click not working on your website. There are multiple reasons why addEventListener could not be working and we can use the following checklist to troubleshoot:
- Make sure the element does exist at script execution - this can trip you up since you are attaching to a null object.
- Verify that your target selector is correct - it needs to be a HTML element that accepts interactive events
- Check the syntax for addEventListener - the âtypeâ is case sensitive, and âhandlerâ must be a function reference
- Check that your handler is not being prevented by another code
- Make sure that the element is interactive and will accept addEventListener events
- Fix other Javascript errors on the page