How to fix - addEventListener is not a function
Common causes of the 'addEventListener is not a function' error in JavaScript and the guide to fix this.
Jul 1, 2023 | Read time 8 minutesđ Table of contents
Introduction
We get the error âaddEventListener is not a functionâ because the element we are targeting is not a DOM element and does not support interactive events.
Some reasons why this error comes up is usually because we are using the function/syntax incorrectly, the element has not exist yet, we are targeting the wrong element or even that the object does not support interactivity.
I came across this error recently with one of my web designs! I was trying to add a alert when someone clicks on a button. Now after a bit of clicking - nothing happened!!
Looking deeper in the browser console, I found that this error âaddEventListener is not a functionâ popped up.
I will go over the ways that I troubleshooted and fixed this error.
Generally, the steps are:
- Verify that you got the syntax right
- Check that the element exists
- Make sure that DOM is ready
- Check if addEventListener is added to âElementâ object
getElementsByClassName()
andquerySelectorAll()
issues
1. Verify that you got the syntax right
Now before we do anything, we want to make sure that we are calling the addEventListener() function correctly.
Hereâs an example of using addEventListener()
:
document.querySelector("#myButton").addEventListener("click", function(event) {
console.log("Button was clicked!");
});
The above code just attaches addEventLister to a button (#myButton) and when the user clicks on the button, it will log to the browser console:
âButton was clickedâ
Generally the addEventListener()
method has three parameters:
- Event Type - this a string that represents the event we want to attach to - eg âclickâ, âblurâ, etc. Now this is required when calling the addEventListener function.
As an example example - If we want to run some code when the user clicks a particular element, we can use âclickâ.
Other examples include âsubmitâ, âkeydownâ, âkeyupâ, âmouseoverâ, etc.
Tip: Keep in mind of case-sensitivity
Make sure that you are not having any typos and check for casing. âClickâ is different to âclickâ - with the former being invalid.
- Listener function - this is required. This function will run every time the event (eg - click, mouseover, etc) triggers. Keep in mind that we are passing the function reference and not the function execution.
So for example if you want to run a function addItem
we should only pass the function without the brackets ()
:
...addEventListener("click", addItem); // âď¸ passing the function reference
...addEventListener("click", addItem()); // â wrong since we are running the function
- The third parameter is the capture which is optional. It is a Boolean indicating whether events of this type will be dispatched to the registered listener before reaching any other EventTarget beneath it in the DOM tree.
The default value is false, which means that the event bubbles up from the target.
If true, the event is captured and goes down from the top of the document to the target.
2. Check that the element exists
Typically the most common reason why âaddEventListener is not a functionâ error comes up is that the element does not exist.
We want to make sure that we are targeting the right element and that it will exist.
Consider the following piece of code:
var myElement = document.getElementById("nonexistentId");
myElement.addEventListener("click", function() {
console.log("Clicked");
});
In this example, if thereâs no element with the ID ânonexistentIdâ, then âmyElementâ is null and you canât add an event listener to null.
3. Make sure that DOM is ready
One thing to make sure is to run the addEventListener function after the DOM has loaded. This is usually with the âDOMContentLoadedâ event:
document.addEventListener("DOMContentLoaded", function() {
var myElement = document.getElementById("myId");
myElement.addEventListener("click", function() {
console.log("Clicked");
});
});
This will ensure that the DOM is fully loaded before we try to add a event listener to the âmyElementâ DOM object.
4. Check if addEventListener is added to âElementâ object
The next common reason why this error occurs is that the addEventListener method is âElementâ objects that can accept interactive events.
If youâre trying to use it on something that isnât a DOM object (like a plain old JavaScript object, or undefined), youâll get this error.
You can use addEventListener on any object that is a Node in the DOM, including elements (objects of class Element), the document object itself, and even the window object.
Hereâs an example of correct usage:
document.getElementById('myButton').addEventListener('click', function() {
console.log('Button was clicked!');
});
However, if you attempt to use addEventListener on a plain JavaScript object, or on other non-DOM objects, it wonât work because those objects donât have an addEventListener method. Hereâs an example:
let myObject = {};
myObject.addEventListener('click', function() {
console.log('This will not work');
});
In this case, youâll get the error myObject.addEventListener is not a function, because addEventListener is not a function thatâs available on plain JavaScript objects.
5. getElementsByClassName() and querySelectorAll() issues
A common problem that I have found is using the getElementsByClassName
and querySelectorAll
functions and then trying to add event handlers to them.
So for example, if we do this - we will get an error:
document.getElementsByClassName("button").addEventListener('click', function() {
console.log('This will not work');
});
Now if we look closely at the getElementsByClassName
and querySelectorAll
functions, we can see that they return a list of DOM objects. However, addEventListener only accepts ONE Element object.
If youâre using document.querySelectorAll or similar to get a collection of elements, youâll need to loop through each one and add the event listener individually.
var buttons = document.querySelectorAll("button");
for(var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
console.log("Button clicked");
});
}
This way, we are using addEventListener as it was intended for ONE element!
Tips for using addEventListener
- Make sure to call removeEventListener when you are finished with the handler
- the âevent typeâ is case-sensitive - so a click event is represented by âclickâ and not âClickâ (with upper casing)
Summary
In this post, I went over how to fix the âaddEventListener is not a functionâ. This error comes up when we are trying to attach an event handler to a non-DOM object that does not accept interactive events.
To fix this we go through our checklist:
- Having the right the syntax to call addEventListener - which takes a case-sensitive string and a function reference
- Make sure that the element exists in the first place or we will be calling to a null object
- Make sure that DOM is ready
- Check if addEventListener is added to âElementâ object. Non-DOM elements such as Javascript objects will not have this function.
getElementsByClassName()
andquerySelectorAll()
returns a list of DOM objects so you will need to loop through them to attach a event handler.