1

I have the code as shown below. Have removed unwanted code from this, just wrote what was needed. When I call my toggleFunc from inline script in body, it shown in console that this function is not defined. Can anyone please tell me whats wrong with this?

<head>
<script src="~/Client/js/lib/jquery-1.10.2.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var pageInitialize = function () {  

            ..doing something here

            function toggleFunc() { 
               ..doing something more here
            };
        };
        pageInitialize();
    });
</script>
</head>
<body>
<script>toggleFunc()</script>
</body>
1
  • 2
    That is because toggleFunc() gets called before it is defined. Commented Jul 14, 2014 at 7:14

3 Answers 3

4

Both your functions will not be defined until DOMReady has fired, which will happen after the call to toggleFunc in the body has been run. Also, toggleFunc is within the pageInitialize function, and is therefore not accessible outside pageInitialize.

Try this:

<script type="text/javascript">
    var pageInitialize = function () {  
        //..doing something here
    };
    pageInitialize();

    function toggleFunc() { 
        //..doing something more here
    };
</script>
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks man, I kind of realized just after posting the question. Stupid question, I ask at times. Thanks anyway.
@RoryMcCrossan Is there a way that if the function is defined then call the function?
@C-linkNepal yes, you can check if the function exists before calling it: functionName && functionName();
No, I meant when the OP calls toggleFunc() inside script then if it is ready to use then call it???
@C-linkNepal no. All you can do is check if a function is available to use at a specific time. There is no way to know when a function become available to you.
1

Two problems:

  1. toggleFunc isn't a global function. It's local to pageInitialize. If you want it to be global, assign it to window.

  2. You're defining the function inside a $(document).ready callback, which will execute at some point in the future. You're invoking the function immediately, outside a $(document).ready callback. It won't have been defined yet.

Comments

0

toggleFunc() is a Closure unable to be called from the global scope.

It's also being called before it's even defined as you are using $(document).ready

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.