0

JavaScript Not Working in Preview

Yumeji 11 years ago in iPad updated 11 years ago 4

While testing iOS editors like Textastic and Koder on the iPad, I noticed that the preview screens never executed my javascript (HTML and CSS were fine). Using the following code as a test:


index.html:


<html>

  <head>
      <title></title>
      <!—for iPad and Komodo—>
      <link href="style.css" rel="stylesheet">
      <script src="script.js"></script>
  </head>
  <body>

        This text will be replaced by Javascript.

  </body>
</html>


script.js:


alert("alert");
document.getElementById("output").innerHTML = "test";


However, when I ran the above code in jsFiddle on the iPad or in Komodo, it seemed to work fine.


Hello,


Textastic does execute JavaScript in the preview screen. Maybe I'm missing something, but there is no element with an id of "output" in the html file, so document.getElementById("output") doesn't work. What happens when you add a div element like this: <div id="output"></div>?

Oops! Looks like a typo in my original post. I actually have a div tag with an id of "output" inside the body. However, it still doesn't work.

The problem is this: your getElementById call is firing immediately, as soon as your JavaScript execution environment is set up, but before the DOM is built, so it returns a null object since the output div doesn't exist yet. You should get the alert though.


There are two ways to solve this: You need to either put the code in a function and use the onload event (either <body onload=...> or window.onload in JavaScript), or you could just put the script tag at the end of the body section instead of in the head section of the html file.


I solved it like this:


script.js:


alert("alert");

window.onload = function (){

    document.getElementById('output').innerHTML = "test";

}


index.html:


<html>

  <head>

      <title>JavaScript Test</title>

      <script src="script.js"></script>      

  </head>

  <body>

      <div id="output">This text will be replaced by Javascript.</div>        

  </body>

</html>

Ah-HA! Thank you so much Alexander! Looks like I'm still a bit green with the JavaScript.