0

What is wrong with this code? I tested it in IE10 and Firefox but the click event was not raised.

  <html>
  <head>
  <title>Sandbox</title>
  <meta http-equiv="Content-type" content="text/html; charset=utf-8" />

  <style type="text/css" media="screen">
  #t1, #t2 { border: 2px solid gray; }
  #t2 { background-color: pink; }
  </style>

  <script>
  // Function to change the content of t2
  function modifyText(new_text) {
    var t2 = document.getElementById("t2");
    t2.firstChild.nodeValue = new_text;    
  }

  // Function to add event listener to table
  var el = document.getElementById("outside");
  el.addEventListener("click", function(){modifyText("four")}, false);
  </script>

  </head>

  <body>
  <table id="outside">
      <tr><td id="t1">one</td></tr>
      <tr><td id="t2">two</td></tr>
  </table>
  </body>
  </html>
PutraKg
  • 2,136
  • 3
  • 29
  • 57

2 Answers2

3

Your JavaScript is running before the DOM is ready:

Uncaught TypeError: Cannot call method 'addEventListener' of null 

You can't reliably interact with the DOM before it's ready, so move your JavaScript to the bottom of the body.

Just in case you were thinking of using window.load = function() {...}, a callback attached to window.load won't run until all of the resources are loaded, which probably isn't what you want. There's no simple plain-JavaScript alternative to jQuery's $(document).ready(), but you could use something from here: $(document).ready equivalent without jQuery

Community
  • 1
  • 1
Blender
  • 257,973
  • 46
  • 399
  • 459
1

Use

window.onload = function() {
  var el = document.getElementById("outside");
  el.addEventListener("click", function(){modifyText("four")}, false);
}
Tamil Selvan C
  • 18,342
  • 12
  • 44
  • 63