GetElementById from external JS file. Using the onclick event handler from input

This isn’t working, tried bunch of different ways. It is from a Javascript beginners book.

html

<input type="button" value="click me" id="say_hi" />

function hi_and_by() {
      window.alert("Hi");
      window.alert("By");
}

document.getElementById("say_hi").onclick = hi_and_by;

also tried this.


function hi_and_by() {
      window.alert("Hi");
      window.alert("By");
}

var hi_button = document.getElementById("say_hi");
hi_button.onclick = hi_and_by;

Neither of them do anything when I click the button.

It will work if you link to the script just before the closing </body> tag. That’s the recommended place for scripts nowadays.

Thank you very much, solved the problem perfectly.

Hi,

if that was exactly what the author of the book told you to do, get your money back. In all likelihood there is worse to come.

If you’re curious, the problem was that the document.getElementById statement was being executed before the page was loaded. You can write javascript within the ‘head’ tags, but if it is meant to interact with something on that page, that something has to exist. So, the rule of thumb is: if the code isn’t a function, it doesn’t belong in the head.