Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'addEventListener' of null

People also ask

What does it mean by Cannot read property addEventListener of null?

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.

Can not read property value of null?

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.

Why does addEventListener not work?

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).

What is document addEventListener?

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