1

I have these simple files -

document.getElementById("btn2").addEventListener("click",function(){
 alert("Did it work?");
});
<html>
<head>
 <title></title>
 <script type="text/javascript" src="myevents.js"></script>
</head>
<body>
 <button id="btn2">Please Work!</button>
</body>
</html>

which work correctly here and also on jsFiddle, but when I run this on my computer locally, the EventListener won't work! I've been trying to fix this all day and no success. What is the problem? I just cannot seem to figure it out!

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Siddharth Thevaril
  • 3,428
  • 2
  • 29
  • 57
  • 2
    Put the ` – Pointy Apr 02 '15 at 16:28
  • @Pointy: It worked. What is the reason for this? Normal javascript runs fine when ` – Siddharth Thevaril Apr 02 '15 at 16:30
  • 1
    @Sidsec9 See the error console. If Pointy's hypothesis is correct (it is my first 'hunch' too) then `getElementById("btn2")` will return null and the line to add the event listener throws a TypeError - and thus the event handler, which is never added, can never be triggered. (JavaScript code can be in head; what *can't* be done is accessing an element *before it exists*.) – user2864740 Apr 02 '15 at 16:31
  • @Sidsec9 browsers build the DOM incrementally as the HTML is parsed. When a ` – Pointy Apr 02 '15 at 16:34
  • Look at your JavaScript console. Look at the error message you get. – Quentin Apr 02 '15 at 21:32

0 Answers0