0

I'm trying to work on some js code to:

  • Create a nav menu
  • Create a header, nav, ul, and li element(s) w/in js
  • Be automatically invoked

Here is the HTML:

<!DOCTYPE html>
<html>
<head>
  <script src="js1.js">
    cHeader();
  </script>
</head>
<body>
</body>
</html>

Here is the js:

function cHeader(){
    var header = document.createElement("header");
    var body = document.getElementById("body");
    body.appendChild(header);
    var ul = document.createElement("ul");
    header.appendChild(ul);
    var li = document.createElement("li");
    ul.appendChild(li);
    var liNode = document.createTextNode("Home");
    li.appendChild(liNode);
}

When I try to call the function by either <body onLoad="cHeader()"> or with <script>cHeader()</script> in the html, my console in Chrome returns with:

Uncaught ReferenceError: cHeader is not defined index.html:19
(anonymous function)

Although, even when I try inline script tags, the code won't do anything.

1
  • you must define the function before you call it... Commented May 12, 2014 at 2:47

2 Answers 2

8
<script src="js1.js">
    cHeader();
</script>

should be:

<script src="js1.js"></script>
<script>cHeader();</script>

<script> tag with src attribute should not contain any thing inside.

Instead, after, loading the script, you need to call it in another <script></script>

Sign up to request clarification or add additional context in comments.

1 Comment

With type="text/javascript" it would be even better
0

try putting window.onload=function(){cHeader();}; at the bottom of your javascript file.

2 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
I think this is an answer; it should fix the issue. I can edit it to explain better, but this is a solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.