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

Leave a Comment