Can not read property 'addEventListener' of null

1

I'm trying to use the scrollleft in my project with the button, it works normal in jsfiddle

But when I put it in my project it returns me this error:

  

Uncaught TypeError: Can not read property 'addEventListener' of null.

    
asked by anonymous 26.05.2017 / 17:46

1 answer

5

Probably in the script on your machine you did not use window.onload or DOMContentLoaded , in jsfiddle it works because the script runs after the load DOM, see how it is in your jsfiddle :

>

Sotofityoucandosomethinglike:

window.onload=function(){varmover=document.getElementById("mover");
    var painel = document.getElementById("painel");

    mover.addEventListener("click", function (event) {
      painel.scrollLeft += 100;
    });
};

Another way with onload would be:

window.addEventListener("load", function () {
    var mover = document.getElementById("mover");
    var painel = document.getElementById("painel");

    mover.addEventListener("click", function (event) {
      painel.scrollLeft += 100;
    });
});
  

addEventListener can make it much easier to use multiple functions with the same event type

Or with something faster:

document.addEventListener("DOMContentLoaded", function () {
    var mover = document.getElementById("mover");
    var painel = document.getElementById("painel");

    mover.addEventListener("click", function (event) {
      painel.scrollLeft += 100;
    });
});

The difference of onload and DOMContentLoaded you can see here:

Alternative to older browsers

If you need something that has the same effect as DOMContentLoaded for older browsers you can try this example:

26.05.2017 / 17:49