0

here is the code, in the console it is telling me that button is null.

<!doctype html>
<html>
    <head>
        <script language="JavaScript" type="text/javascript" src="test.js"></script>
    </head>
    <body>
        <button type=button id="button">Click me</button>
    </body>
</html>

Here is the javascript test.js

function showAlert(){
    alert("this is an alert");
}

var button = document.getElementById("button");

button.addEventListener("click", showAlert);
Adam Piper
  • 505
  • 1
  • 5
  • 11

1 Answers1

2

test.js is being included before the <button> element. So, when the script is being executed, the element isn't there. So include your <script> after the element which you're accessing in it is declared.

<!doctype html>
<html>
    <head></head>
    <body>
        <button type=button id="button">Click me</button>
        <script language="JavaScript" type="text/javascript" src="test.js"></script>
    </body>
</html>
Amit Joki
  • 58,320
  • 7
  • 77
  • 95