Carla
Carla

Reputation: 3380

Unable to call function from external JavaScript

I have a simple HTML page which calls a JavaScript function:

<!DOCTYPE html>
<html>
    <script type="text/javascript" src="css/myscript.js"></script>
    <head>
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body onload="javascript:hello()">
    </body>
</html>

This is my hello() function:

<script>
function hello() {
    alert("load new content");
    document.open();
    document.write("<h1>Changed content!</h1>");
    document.close();
}
</script>

When pasting the JavaScript block into the page directly, it works. However it's not able to find hello() if the JavaScript is contained within a dedicated file.

Using the Developer tools I can see that the JavaScript file is loaded successfully.

Upvotes: 0

Views: 65

Answers (3)

Jake Reece
Jake Reece

Reputation: 1168

The contents of myscript.js should just be:

function hello() {
  alert("load new content");
  document.open();
  document.write("<h1>Changed content!</h1>");
  document.close();
}

You would include the <script> tag only if your JavaScript were inside your HTML file; the <script> is what tells the browser, "Hey, we're not interpreting HTML anymore. This is JavaScript."

Also, as Colin pointed out in the comments, myscript.js probably doesn't belong in your css folder. A common name for the folder that contains all your website's JavaScript files is js.

Upvotes: 1

ibrahim tanyalcin
ibrahim tanyalcin

Reputation: 6491

2 issues, during parsing of your script, document is already open. If you open again, everything will be deleted so get rid of it(write is already a call to open). Second, make sure you do not add the script after the load event, so that function hello is really defined. Here I am adding it right within body (or you can use defer if you want.) Here is the fiddle

<head>
  <link rel="stylesheet" href="css/style.css">

</head>
<body onload="hello();">
</body>



 function hello() {
      alert("load new content");
      //document.open();
      document.write("<h1>Changed content!</h1>");
      document.close();
    }

Upvotes: 1

TGr
TGr

Reputation: 36

If you have those script tags in your js file, get rid of them.

Upvotes: 1

Related Questions