I want to provide helper functions that allow various components of a complex jQuery-based UI to hide or show a loading div (used when an Ajax call is initiated from various portions of the page).
To that end, I initially wrote code like this:
<script type="text/javascript">
$(function ()
{
var loadingControl = $("#loading");
function showLoading() {
loadingControl.show();
}
}
</script>
However, I quickly realized that showLoading is only in scope within that particular document ready.
Following the advice from
https://stackoverflow.com/a/1055799/141172
I declared showLoading in global scope like this:
<script type="text/javascript">
var showLoading;
$(function ()
{
var loadingControl = $("#loading");
function showLoading() {
loadingControl.show();
}
}
</script>
However, I still find that showLoading is not available in document ready blocks that execute later. The error is
The value of the property 'showLoading' is null or undefined, not a Function object
This behavior can be seen here:
The jsFiddle also proves that the showLoading implementation's document ready runs before the document ready block that calls it.
What is going wrong, and how can I make this helper method available?
I define it within a document ready block because it relies on '#loading' being available. Is there a better approach to accomplishing the same goal of providing a helper function to hide/show the loading screen? I want to keep this in a helper function because the implementation may change later.