-1

I am trying to get the HTML file to print the output of a javascript file but it doesn't seem to be working - I just end up with a blank page.

My HTML file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="sketch.js"> setup()</script>       
</head>
<body>
    <div id="fog"></div>
</body>
</html>

My javascript file (sketch.js)

function setup() {
    s = "hello";
    document.getElementById('fog').innerText = s;        
}
piccolo
  • 2,093
  • 3
  • 24
  • 56
  • Possible duplicate of [What does a script-Tag with src AND content mean?](https://stackoverflow.com/questions/6528325/what-does-a-script-tag-with-src-and-content-mean) – Ivar Jul 15 '18 at 23:39
  • Use one ` – Ivar Jul 15 '18 at 23:40

2 Answers2

1

Include the script calling setup near the closing body tag,the dom with id fog is not present when setup is called

    <head>
     <meta charset="UTF-8">
     <script src="sketch.js"></script>       
    </head>
    <body>
     <div id="fog"></div>
    <script>setup()</script>
    </body>
brk
  • 48,835
  • 10
  • 56
  • 78
1

Your script tag is synchronous, means that the parser waits and executes the contents of the script BEFORE the html is fully parsed. By the time your script is executed the div is not even there. If you do not want to defer the script or change its location, you can at least use DOMContentLoaded event:

window.addEventListener(
    "DOMContentLoaded",
     function setup() {
          var s = "hello";
          document.getElementById('fog').innerText = s;        
     },
     false
);

in your script.

ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22