jQuery - function inside $(document).ready function

Yes, you can do that, it's just a matter of scope.

If you only need to access callMe() from within $(document).ready(function() { }), then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context.

If you need to use the callMe() function outside of document ready though, you need to define the callMe() function outside of that context.

function callMe() {
  // Do Something
}

$(document).ready(function() {
  callMe();
});

UPDATE

Based on your clarification, you have two options:

1) DECLARE variable outside of ready(), but then define variable inside of ready():

var someVariable;
function callMe() {
  someVariable++;
  alert(someVariable);
}

$(document).ready(function() {
  someVariable = 3;
  callMe(); // Should display '4'
});

2) Within ready(), define variables using window.yourVariable = 'whatever';


When you create a function inside $(document).ready, it's guaranteed that it won't be called before the document has loaded. Of course, it can only be called from that event handler itself (somewhere later in the event handler).

In other words, what you're trying to do is valid (though not necessarily desirable - you'd have to reveal more about what you are trying to accomplish).


This will also work.

$(document).ready(function() {
      callMe = function() {
            alert('hello');
      }
});

callMe();

If you use

 var callMe = function () { ... }

It may not work and you may get an error "function is undefined"