whyAto8
whyAto8

Reputation: 1670

jquery - function not defined - calling this function from inline script

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>

Upvotes: 1

Views: 1462

Answers (3)

Teh SoTo
Teh SoTo

Reputation: 209

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

Upvotes: 0

user229044
user229044

Reputation: 239382

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.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337626

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>

Upvotes: 4

Related Questions