Jquery: Calling functions from different documents

Tom picture Tom · Apr 17, 2010 · Viewed 19.3k times · Source

I've got some Jquery functions that I keep in a "custom.js" file. On some pages, I need to pass PHP variables to the Jquery so some Jquery bits need to remain in the HTML documents. However, as I'm now trying to refactor things to the minimum, I'm tripping over the following:

If I put this in my custom.js:

$(document).ready(function()
{
   function sayHello() {
      alert("hello");
   }
}

And this in a HTML document:

<script type="text/javascript">
   $(document).ready(function()
   {
      sayHello();
   });
</script>

... the function doesn't get called. However, if both are placed in the HTML document, the function works fine.

Is there some kind of public property I need to declare for the function or how do I get Jquery functions in my HTML to talk to external .js files? They're correctly included and work fine otherwise.

Thanks.

Answer

wsanville picture wsanville · Apr 17, 2010

The problem is you're defining sayHello within the anonymous function that is declared on this line:

$(document).ready(function()

As a result, sayHello is scoped to only that function. If you wish to call sayHello from anywhere else in your application, such as the HTML on your page or another line in custom.js, you will need to change custom.js and define it outside the call to $(document).ready:

function sayHello()
{
   alert("hello");
}

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