Index.html not finding javascript file

Hi,

I have two files in a folder- one is index.html and the other is myscript.js. The index.html is not finding the javascript. The content of both files are as follows-

html code-

<html>
<head>
<meta charset="utf-8"><title>my webpage</title>
<script src="myscript.js" type="text/javascript"></script>
</head>

<body>
<button id="button">click me</button>

</body>
</html>

and javascript,

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

function change(){
  document.body.style.background = "yellow";
}
button.addEventListener("click",change);

Why is that so?

Because you are loading the script at the top of the page, before the button has been loaded in the browser, the browser can’t set a value for the button var, because when it looks, there’s no button.

The standard practice these days is to attach the script to the bottom of the file—which is the easiest way to deal with this:

<html>
<head>
<meta charset="utf-8"><title>my webpage</title>

</head>

<body>
<button id="button">click me</button>


<script src="myscript.js" type="text/javascript"></script>
</body>
</html>

thanks, it works now

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.