user3437460 user3437460 - 9 days ago 5
HTML Question

Unable to call javascript function from another script block

I have 2 script blocks (written in the same file), however I am unable to call the function written in another script block.

<!DOCTYPE html>
<html>
<head>
<title>Just A Test</title>
</head>

<body>
<div class="app">
<h1>Just A Test</h1>
</div>

<div data‐role="main" class="ui‐content">
<form name="testForm" id="testForm">
<div class="ui‐field‐contain">
First greeting:
<script type="text/javascript">
greetings1(); //ERROR AT THIS LINE
</script>
<p></p>

</div>
</form>
</div>

<script type="text/javascript">

function greetings1(){
alert("Hello ONE");
}

</script>
</body>
</html>


The error I get is:


Error: 'greetings1' is undefined


My question is: What is causing the browser not being able to see the declared function? I have spent hours and tried ways such as moving the script block to the
head
, but the problem still persist.

Answer

We pages are parsed from left to right, top to bottom. You are declaring your function after the call for it. Move the function declaration so that it is processed BEFORE the call for it to run. You can do this by picking up the entire script block and moving it into the head.

If we replace your "inline" call to your function with DOM injection, we can place the script at the bottom of the page, but we need to modernize your code with event handlers:

<!DOCTYPE html>
<html>
    <head>
        <title>Just A Test</title>
    </head>

    <body>
        <div class="app">
            <h1>Just A Test</h1>
        </div>

        <div data‐role="main" class="ui‐content">
            <form name="testForm" id="testForm">
                <div class="ui‐field‐contain">
                    <!-- NOTE THE ADDITION OF THE  SPAN -->
                    First greeting: <span id="greeting"></span>

                </div>
            </form>
        </div>

        <script type="text/javascript">
          // By the time the browser parses down this far, the SPAN will have
          // been read into memory:

          // Get a reference to the span:
          var span = document.getElementById("greeting");
          
          // Just for fun, let's ask the user what their name is:
          var name = prompt("What is your name?");
          
          // Inject that answer into the SPAN
          span.textContent = name;
          
          // Display an alert with the name:
          alert("Hello " + name);

        </script>
    </body>
</html>