1

First I'm sorry, because I'm certain that this has been asked many times, I just don't know how to search for this.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
    </head>
    <body>

        <form>
            <button type="button" onclick="hello()">test1</button>
            <button type="button" id="test2">test2</button>
            <h1 id='myText'></h1>

        <script type="text/javascript">
            function hello() {
                document.getElementById('myText').innerHTML = 'test1';
            }
            document.getElementById('test2').onclick = function(event) {
                document.getElementById('myText').innerHTML = 'test2';
            }   
        </script>
        </form>     
    </body>
</html>

This is my code. Before this version the whole script-tag was within the head area, and only test1 worked, test2 did nothing.

  1. Can you point me on where to read up on why that is so?
  2. Also, is there a preferred method of the two, to trigger an event?
Juan Picado
  • 1,314
  • 13
  • 29
inane
  • 33
  • 2

1 Answers1

0

It's the order in which the elements are processed.

In very simple terms: stuff in <head> loads up before the stuff in <body>, likewise, stuff at the top of <body> will load before stuff at the end of <body>. For this reason, where you're trying to grab an element with an ID of test2, your #test2 event handler will only work when the #test2 button has been loaded before your <script>; otherwise it simply doesn't exist on the page at this point.

James Donnelly
  • 117,312
  • 30
  • 193
  • 198