.addEventListener won't be added everytime the page loads

On loading a page I add an event listener to a form.

window.onload=function()
{
  document.getElementById("login").addEventListener("submit", function(event){
    event.preventDefault()
  });
}

When I reload the page it sometimes works and sometimes I get the message Cannot read properties of null (reading 'addEventListener').
It’s about a 50/50 chance.

What could be the problem here?

>Solution :

Based on yours (and @Jaromanda X’s helpful) comments, perhaps instead use a callback function in the .load to bind the event listener?

$('#loginModalDiv').load("loginModal.html", function() {
  document.getElementById("login").addEventListener("submit", function(event){
    event.preventDefault()
  });
});

Leave a Reply