The "Cannot read property addEventListener of null" error occurs when trying to call the addEventListener() method on an element that isn't present in the DOM. Variables that store a value of null are often returned from methods such as getElementById() when the element is not present in the DOM.
The "Cannot read property 'click' of null" error occurs when trying to call the click method on a null value. To solve the error, run the JS script after the DOM elements are available and make sure you only call the method on valid DOM elements.
The "addEventListener is not a function" error occurs for multiple reasons: calling the method on an object that is not a valid DOM element. placing the JS script tag above the code that declares the DOM elements. misspelling the addEventListener method (it's case sensitive).
The addEventListener() method attaches an event handler to a document.
I think the easiest approach would be to just check that el
is not null before adding an event listener:
var el = document.getElementById('overlayBtn');
if(el){
el.addEventListener('click', swapper, false);
}
It seems that document.getElementById('overlayBtn');
is returning null
because it executes before the DOM fully loads.
If you put this line of code under
window.onload=function(){
-- put your code here
}
then it will run without issue.
Example:
window.onload=function(){
var mb = document.getElementById("b");
mb.addEventListener("click", handler);
mb.addEventListener("click", handler2);
}
function handler() {
$("p").html("<br>" + $("p").text() + "<br>You clicked me-1!<br>");
}
function handler2() {
$("p").html("<br>" + $("p").text() + "<br>You clicked me-2!<br>");
}
I faced a similar situation. This is probably because the script is executed before the page loads. By placing the script at the bottom of the page, I circumvented the problem.
script is loading before body, keep script after body
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With