Laura
Laura

Reputation: 4369

Call a function inside $('document').ready

I have a function defined inside a $('document').ready.

$('document').ready(function() {
  function visit(url) {
    $.ajax({
      url: url,
      container: '#maincontainer',
      success: function(data) {
        init();
      }
    });
  }

  function init() {
    ...
  }
)};

But when I call init() in Chrome Console I get : ReferenceError: init is not defined.

Update: Thank you all for your help. I didwindow.init = init; and it works perfectly.

Upvotes: 2

Views: 6454

Answers (5)

Joao Almeida
Joao Almeida

Reputation: 982

Try something like this:

$('document').ready(function() {

  var objScope = this;

  function visit(url) {
    $.pjax({
      url: url,
      container: '#maincontainer',
      success: function(data) {
        objScope.init();
      }
    });
  }

  function init() {
    ...
  }
)};

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074949

Your init function is contained by the scope of the function you've passed to jQuery.ready. This is a good thing, it means you haven't created an unnecessary global.

If you need to export the function to the global scope, you can do so by explicitly assigning to a property on window, e.g.:

window.init = init;

Since window is the global object on browsers, that would allow you to call it from Chrome's console without the window. prefix. But only do that if absolutely necessary, the global scope is already crowded enough.

Upvotes: 6

Michael Erickson
Michael Erickson

Reputation: 4445

I think you want to put your function definition outside the ready function, it is not necessary for the document to be ready to define a function even if the function references the document. Keep in mine the references inside a function are not performed until the function is actually executed, a function definition is just like defining a text constant. Use the following instead:

function visit(url) {
    $.pjax({
        url: url,
        container: '#maincontainer',
        success: function(data) {
        init();
        }
    });
}

function init() {
    ...
}

$(function () {
    init();
});

Upvotes: 0

Twisol
Twisol

Reputation: 2772

Function declarations, like your function init() {}, are restricted to the scope they're defined in. If you want to use init elsewhere, do this:

var init;
$('document').ready(function() {
    init = function() {};
});

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

Functions are only defined the scope you define them in.

If you insist on this method, use init = funciton() syntax instead. This will create a global variable (since you're not going to put a var there) which can be referenced anywhere.

That said, defining functions can be done at any time, there is absolutely no point in putting them in .ready().

Upvotes: -1

Related Questions