I have some functions in a JQuery document ready method that I would like to reference from other external files, but I keep getting a function undefined. How can I make those global?
ex.
external file 1
$(function ()
{
function DoSomething()
{
Do something
}
});
external file 2
$(function ()
{
Call DoSomething()
)};
declare the functions outside the jQuery escope.
external file 1
function DoSomething()
{
Do something
}
external file 2
$(function ()
{
Call DoSomething()
)};
You can either define the function outside .ready() (as the other answers suggest), or you can take advantage of the fact that the window object is the global scope. So, you can make them global like this:
$(function(){
function doSomething(){
// …;
}
window.doSomething = doSomething;
});
Note that in this case they’ll only be defined after .ready() runs — if you want to use them immediately in another file (i.e. not inside an event handler or another .ready() function), this won’t work.
You probably want to define functions outside ready blocks. That does not hurt. Only executing a function outside a ready block can cause issues if it uses the DOM before it's ready.
Defining does nothing (yet), and as such does not use the DOM. So it does not need to be inside a ready block; doing so only constrains the places where you can access it, which is basically only a disadvantage.
external file 1
function DoSomething()
{
Do something
}
Whenever possible, declare functions outside of the ready check.
external file 1
function DoSomething()
{
Do something
}
external file 2
$(function ()
{
Call DoSomething()
)};
Related
I'm having some issues with running some functions from an external js file.
The html includes:
<script src="js/file.js"></script>
<script>
$("#center-button").click(function() {
explodePage("center");
});
</script>
The js file includes:
var explodePage = function(button) {
//code here
aboutPage();
}
var aboutPage = function() {
//code here
}
The explodePage function runs fine, but as soon as it reaches the call to the nested aboutPage function, it starts throwing these uncaught typeerrors at me. It works fine if I don't use an external js file and just put everything into the html. Pretty new to this so probably missing something obvious in scope or something. Any solutions?
Declare the function's definition as below:
function explodePage(button) {
//code here
aboutPage();
}
function aboutPage() {
//code here
}
Explanation:
When you use the var keyword for declaring functions, the execution of JS happens as when the variable is initialized, you cannot reference or use variable's before declaration. In contrast with the name function defintion JS interpreter first picks the enclosed functions before execution and initializes it before the code execution. This is called AST- Abstract syntax tree that is followed by JS interpreters.
Also Remember:
Also bind your Jquery code inside a Jquery document ready function, just to make sure the Jquery and the DOM elements are available for the bindings.
It's not a good a idea to pollute the global window object with variables, since there can be collisions. And immediately-invoked function expression is a good solution for this.
(function(){
//You can declare your functions in here, and invoke them below
$( document ).ready(function() {
//Check that the DOM is ready, in order to manipulate it an add events
$("#center-button").click(function() {
explodePage("center");
});
});
})($); //Notice that we are injecting a dependency, in this case jQuery
I current have some code that looks like this:
// when the document is ready
execute myFunction();
(function($){
function myFunction()
{
// code
};
})(jQuery);
The console is saying that myFunction is not defined...why?
It's not accessible because you've put your function inside another self-invoking function, and the call to it is outside that.
Your comment states that you want the call to myFunction() to happen on load, which if your current code worked, would not be the case anyway. It would call the function before DOMReady.
To get the behaviour you want, place the function call within the SIF:
(function($){
myFunction();
function myFunction() {
// code
};
})(jQuery);
I see
First
$(function() {
...
});
Second
(function() {
})();
Third
function() {
}
$(document).ready(function(){
});
Maybe there are more, what are the differences?
Your notation is mainly jQuery (atleast the ones with $)
This is shorthand for a DOM ready function, equivalent to the bottom one
This is a self executing function with the parameter specified in the trailing ()
This is a DOM ready function $(document).ready(function() {}); atleast, the function above it is simply a function.
so these indeed are a few different ways to execute javascript code, some of them are library dependent (using jQuery) others are done specifically because of differences in scope.
the first block:
$(function() {
...
});
is utilizing the js library jQuery that uses the namespace '$' what you are doing here is calling the jQuery '$' function passing in the first parameter of another anonymous function... this is a shorthand way to call $(document).ready(function(){});... both of those statements wait for the DOM to complete loading (via the onload event) before interpreting the javascript inside
the second block:
(function() {
})();
is a procedure called an (IIFE) Immediately-Invoked Function Expression... which in essense is defining an anonymous function and calling it immediately.
the third block:
function() {
}
$(document).ready(function(){
});
represents two things... the first function declared actually should have been named something like function myFunction(){...} and thus could be called later myFunction(parameters);
and finally $(document).ready(function(){}); is the javascript library jQuery's way of saying grab the 'document' element of the dom, and attach an event listen to it looking for the onload event, when that event is triggered execution the function passed as a parameter...
Say I add to First.js:
$(document).ready(
function () {
dosomething A
});
function () {
dosomething C
});
});
and to Second.js:
$(document).ready(
function () {
dosomething B
});
});
will all 3 functions be executed after DOM is ready?
What will be the case when I register
to First.js:
$(document).ready(
A = function () {
dosomething A
});
C = function () {
dosomething C
});
});
to Second.js:
$(document).ready(
A = function () {
dosomething A
});
});
The later will override the first?
TIA
Your first example is invalid syntax. It will cause the javascript interpreter to throw an exception. You need to pass one and only one function to $(document).ready(fn). You can include multiple function calls inside the one function, but you can only pass one function to .ready().
Your second example is also a syntax error - an extra });. If that is removed, it will work and execute that one function.
Your third example in both first.js and second.js is also a syntax error. You can't put arbitrary javascript as the parameter to .ready(). It must be one function reference with proper syntax.
Now, what you may have been trying to ask if you actually provided legal syntax in your examples is that all functions you pass to .ready(fn) will be executed when the document is ready. jQuery keeps an array of all functions that have been passed and executes them all when the document becomes ready. The jQuery documentation for .ready() does not specify the calling order if .ready() has been called multiple times with multiple functions, though one could examine the source code and see what the order is likely to be.
"will all 3 functions be executed after DOM is ready?"
Yes. Each time you bind something to be executed at DomReady, jQuery will queue the function in an internal array, then execute them in the same order as they where "inserted".
The later will override the first?
Yes it will, unless you put var before the definition. JavaScript will put A in the window scope, so the next definition will override the first.
function() {
var A = 0; // this will only exist within the function
}
function() {
A = 1; // this will be added to the "global" scope (window).
}
The later will override the first?
No, you can assign multiple functions to individual events.
I'm assuming your syntax errors were unintentional. The way they are written, NO code is executed.
Yes, you can bind the same event several times without problems.
Yes, the second code will replace the value set by the first code.
Before I heard about self executing functions I always used to do this:
$(document).ready(function() {
doSomething();
});
function doSomething()
{
// blah
}
Would a self executing function have the same effect? will it run on dom ready?
(function doSomething($) {
// blah
})(jQuery);
Nope. A self executing function runs when the Javascript engine finds it.
However, if you put all of you code at the end of your document before the closing </body> tag (which is highly recommended), then you don't have to wait for DOM ready, as you're past that automatically.
If all you want is to scope your $ variable, and you don't want to move your code to the bottom of the page, you can use this:
jQuery(function($){
// The "$" variable is now scoped in here
// and will not be affected by any code
// overriding it outside of this function
});
It won't, it will be ran as soon as the JavaScript file is executed.
No, self-executing javascript functions run right there.
If you want to create a DOM ready function, write the following:
$(function() {
// this will run on DOM ready
});
Which is a shorthand of:
$(document).ready(function() {
});
No, the self-executing function run immediatly after you "declare" it on your code. Even if it's located on an external .js file.
In your example, there is a possibility that your function will execute and the value of jQuery is undefined. If you want your code to be executed on DOMReady, continue using
$(document).ready(function(){
doSomething();
});
or
$(function(){
doSomething();
});
or even
window.onload = function(){
doSomething();
}
$(document).ready(function() { ... }); simply binds that function to the ready event of the document, so, as you said, when the document loads, the event triggers.
(function($) { ... })(jQuery);
is actually a construct of Javascript, and all that piece of code does is pass the jQuery object into function($) as a parameter and runs the function, so inside that function, $ always refers to the jQuery object. This can help resolve namespacing conflicts, etc.
So #1 is executed when the document is loaded, while #2 is run immediately, with the jQuery object named $ as shorthand
$(document).ready(function(){ ... }); or short $(function(){...});
This Function is called when the DOM is ready which means, you can start to query elements for instance. .ready() will use different ways on different browsers to make sure that the DOM really IS ready.
(function(){ ... })();
That is nothing else than a function that invokes itself as soon as possible when the browser is interpreting your ecma-/javascript. Therefor, its very unlikely that you can successfully act on DOM elements here.
jQuery document.ready vs self calling anonymous function