Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple event listener not working - JS [duplicate]

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)

like image 528
user2594377 Avatar asked Jul 18 '13 07:07

user2594377


People also ask

Why is my event listener not working?

If your event listener not working is dependent on some logic, whether it's about which element it'll listen on or if it's registered at all, the first step is to check that the listener is indeed added to the element. Using a breakpoint in the developer tools , a logpoint or console.

Can I have two event listeners in JavaScript?

You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.

Does event listener works only once?

Using the once option We can pass an object as an argument to the addEventListener method and specify that the event is only handled once. This is achieved by passing the property once to the object. If we set once to true, the event will only be fired once.


1 Answers

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)

like image 82
Plato Avatar answered Oct 19 '22 04:10

Plato