0

I'm trying to separate my scripts and styling from my markup, but I can't seem to get away from an onclick attribute. From all the searching I've done on Google and StackOverflow, this script should work. How do I make the onclick event completely separate from my markup?

<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById('guest_button').onclick = function () {
    document.write('You\'re a guest!');
}
</script>
<title>Test</title>
</head>

<body>
  <div id="prompt-container">
    <form>
      <input id="guest_button" type="button" value="Guest">
        <input type="button" value="Login">
        <input type="button" value="Sign Up">
      </form>
    <div id="test"></div>
  </div>
</body>
</html>
Zac Canoy
  • 102
  • 12
  • 1
    You must have got an error on the console because `document.getElementById('guest_button')` returned null. That should have guided you. Always check the console. – Ruan Mendes Dec 11 '14 at 23:16

1 Answers1

1

You have to wait until the DOM element you are targeting has been loaded before you can attach an event to it. The easiest way to do that is to move your script tag AFTER the relevant HTML.

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>

<body>
  <div id="prompt-container">
    <form>
      <input id="guest_button" type="button" value="Guest">
        <input type="button" value="Login">
        <input type="button" value="Sign Up">
      </form>
    <div id="test"></div>
  </div>
<script>
document.getElementById('guest_button').addEventListener("click", function () {
    alert('You\'re a guest!');
});
</script>
</body>
</html>

Note, I also switched your code over to use addEventListener() and switched to an alert() since document.write() after the document has been loaded will clear your document.

For more info about waiting for the DOM to be loaded before attempting to operate on it, ready this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979