Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Calling functions from different documents

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.

like image 975
Tom Avatar asked Apr 17 '10 01:04

Tom


2 Answers

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();
}
like image 158
wsanville Avatar answered Nov 15 '22 23:11

wsanville


just make the function a global variable

sayHello=function() {
    alert("hello");
}
like image 38
user995789 Avatar answered Nov 16 '22 00:11

user995789