javascriptjquery

jQuery function calling


I'm trying to have a callback call a function inside $(document).ready(..)

How do I call a function from outside this?

Like for example:

$(document).ready( function(foo) {
   var bar = function() { ... };
});

// How do I call bar() from here?

Solution

  • That depends on how you want to scope things. If you just want bar to be in the global scope, then just do this:

    $(document).ready( function(foo) {
       var bar = function() { ... };
       window.bar = bar;
    });
    

    Remember, in JavaScript the only code blocks that have scope are functions, so variables declared in if{}, while{}, and other types of code blocks are global to whatever function they are a part of, unless they are not declared.

    If you use a variable without declaring it, that is the same as doing:

    // Both of these variables have global scope, assuming
    // 'bar' was never declared anywhere above this
    window.foo = "Hello World!";
    bar = "Hello World!";
    

    So the example above could be a line shorter by doing:

    $(document).ready( function(foo) {
       window.bar = function() { ... };
    });