When creating functions for re-use, is it possible to create a function inside the:
$(document).ready(function () {
});
block of code?
When creating functions for re-use, is it possible to create a function inside the:
$(document).ready(function () {
});
block of code?
Yes, but they can't be referenced outside of there, for example:
$(document).ready(function () {
function myFunc() { }
$(".class").click(myFunc);
//or myFunc();
});
Is valid, where as this wouldn't be:
$(document).ready(function () {
function myFunc() { }
});
myFunc();
Or the more common inline issue, where it can't access the function as a result of scoping:
<button onclick="myFunc()">Something</button>
the syntax
xy = function() {
}
allways creates a globaly accessable function (if the variable was not initialized before). But you should not create functions inside $(document).ready(); as there is no need to wait for the DOM to load the function. Into $(document).ready(); you put code you want to execute if the complete HTML became loaded by the browser.
Maybe you mean the "own scope" syntax:
(function($) {
/* code */
})(jQuery);
But also there: If you want to have global functions, why put them into a local scope? :-)
Yes. There is even a way to use it outside of that block:
var gs = {}
gs.func = function() {} // A dummy to avoid errors
$(document).ready(function () {
gs.func = function() {...} // redefinition when the document is ready
});
This way, you can use gs.func() everywhere, it just won't do anything until the page has loaded.