10

I have written an increbily simple event listener and yet it comes up with the error: Uncaught TypeError: Cannot call method 'addEventListener' of null which suggests it is to do with the id maybe (also it works with document?

<html>
<head>
    <script type="text/javascript">
        function message () {
        alert("Hello!");
        }
        var button = document.getElementById('button');
        button.addEventListener('click', message, true);
    </script>
</head>
<body>
    <input type="button" id="button" value="Click me!" />
</body>
</html>

(I know I'm going to feel stupid after this, but I am a JS noob)

user1882981
  • 180
  • 1
  • 2
  • 15
user2594377
  • 111
  • 1
  • 1
  • 4

2 Answers2

13

at the time your script executes, the DOM has not been created. you can place your script after the body tags to run it after reading the html - but the better way to do it is by listening for DOMContentLoaded.

document.addEventListener('DOMContentLoaded', init, false);
function init(){
  function message () {
    alert("Hello!");
  }
  var button = document.getElementById('button');
  button.addEventListener('click', message, true);
};

window.onload = init works too. I don't like it because it looks to me like one script could overwrite window.onload to be its own init function. (i haven't confirmed that happens or not)

Plato
  • 9,788
  • 2
  • 36
  • 58
2

Because this script is executed when body isn't loaded yet. Use onload event, and within it paste your code.

user1882981
  • 180
  • 1
  • 2
  • 15