2

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.

2
  • Down voter, care to explain? This has not been asked before. I know this is a basic question, but I have spent a lot of time researching on this and I am new to this, so please. Commented Dec 1, 2016 at 19:42
  • I don't understand either. This is a well formed, clear question, with a definite answer. +1. If there's a duplicate of this somewhere, please vote to close or flag it as such. Commented Dec 1, 2016 at 19:42

4 Answers 4

3

Web pages are parsed from left to right, top to bottom. You are declaring your function after the call for it. You have two solutions here:

  1. 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.

  2. 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. This is the preferred approach because it removes the JavaScript from being interspersed with the HTML.

<!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
                         AND THE REMOVAL OF THE JAVASCRIPT -->
                    First greeting: <span id="greeting"></span>

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

        <script type="text/javascript">
          // Now, all your JavaScript will be separated away from your HTML
          // and won't run until after all the HTML elements have been 
          // parsed and are in memory

          // 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>

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

2 Comments

Thanks, I appreciate your reply on this. +1
@user3437460 Check out my updated answer that addresses why you saw that scripts should be at the bottom of the page and how to properly do that.
1

Try first declare the function then call it. Browser reads and executes your code line by line, so when it reaches to the greetings1();, it doesn't find any function with that name. But when you declare your function first, it finds the name and executes it.

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

<body>
  
    <script type="text/javascript">

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

    </script>
  
    <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>

    
</body>
</html>

4 Comments

Thanks for the reply, initially I placed it on top. However I read some post from SO and someone mentioned it is a good practice to place the script block just before the end of the the body. So as a practice, should I just place it at the top?
@user3437460 if you have external js file, put in in the bottom, but if you have inline js code you need to put them according to your logic. But always try to separate js code from html
@SurenSrapyan "if you have external js file, put in in the bottom," Even if the script was an external file, it would still fail in this example because the function would still be invoked prior to the script.
Appreciate your reply on this +1
0

First of all you should use external javascript. But anyway the error is you have to declare the function before calling it in the html

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

<body>


<script type="text/javascript">

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

</script>

<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>


</body>
</html>

5 Comments

Why "should" external JavaScript be used? What if the function is only applicable to the current page?
Your answer doesn't include any body tags.
It runs faster, code looks cleaner, the user has only to load once the script file
"It runs faster" you need another HTTP request, so definitely not. The only advantages for external scripts are caching and reuse across different pages.
It does not run any faster than if it were in the page. The extra HTTP call is going to actually delay the entire page load time. External scripts are for code reuse, yes. But for page-specific code, internal scripts are absolutely the right thing to do.
-1

After spending hours, I found another problem which may cause the

function is undefined error

In my script block, there is an EXTRA SEMICOLON in one of the statements from one of the functions:

<script type="text/javascript">

    function greetings(){
        alert("HELLOOOOOOO!");
    }

    function calcDebtToIncomeRatio(){
        //some other codes not shown
        var income = parseFloat(localStorage.getItem("income");); //<--- EXTRA SEMICOLON
        return (repayment / income);
    }
</script>

I am writing this solution here, hopefully it will be useful to someone in the future.

Comments

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.