I have a similar question before, my question was about how to access all the JavaScript functions in the web browser console even if they were within window.onload = function() {// code and functions} , but this time I want to do the same thing with jQuery:
$(document).ready(function() {
// I want to access all the functions that are here in the web console
})
You can use the same syntax as in your previous question. Simply assign the function to the window.
The following example illustrates what I mean. Note that you do not need the setTimeout(), this is just for this example here to auto-execute the your_function() when it is defined.
$(document).ready(function() {
window.your_function = function(){
console.log("your function");
};
your_function();
});
// setTimeout() is needed because the $.ready() function was not executed when
// this code block is reached, the function(){your_function();} is needed because
// the your_function() is not defined when the code is reached
setTimeout(function(){
your_function();
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note 2: I suggenst not to define global functions in the $(document).ready() if there is not a good reason for it. You can define the functions outside and then call them in the $(document).ready().
Related
I want to execute a function which was defined in the start of the script, lets call this function initialize. This function also uses a variable, lets call it login, which is defined by a php file that includes my jquery script file after defining the variable login.
php/html:
<script type="text/javascript">
login = '<?php echo $login; ?>';
...
</script>
<!-- script is included -->
<script type="text/javascript" src="script.js"></script>
jquery:
function initialize(){
$("." + login).remove();
}
jQuery.moreContent = function moreContent()
{
//more content is loaded
...
initialize();
}
the moreContent function is then loaded, I can see more content appearing on my screen but initialiye is not loaded. only if I use a function like resize (in the end of the script.js file) it works
jquery (in the end of script):
//load function initialize
initialize();
//this function doesnt work too, I tested if it even loads and it does (used a number that was increased by one whenever function was loaded which actually happened...)
//however the wished element with the class of variable login is not removed
//resize function
$(window).resize(initialize);
//this one suddenly works
...
I have no idea why it suddenly works with the other function and why it doesnt work in the other cases
You need to wrap your code and make it run once the document is ready, like this:
$(document).ready (function(){
// run all your functions here
});
Maybe the variable login is empty in the other function, or you are giving thst a different value.
Try with a global variable to test it, like
window.login = script_php
And try again, in this ways, the login variable is global, or pass this variable as a parameter in the function.
the moreContent function is then loaded, I can see more content appearing on my screen but initialize is not loaded.
That is not exactly what happened. You have attached a function as method directly to jQuery object but did not invoke it,
jQuery.moreContent = function moreContent()
{
//more content is loaded
...
initialize();
}
You won't get any fruitful benefit from doing it this way. You have just added a method to an object (jQuery in this case) which is not invoked yet. In any case you do not need to add it as a method to jQuery object itself. You can do it easily without this as following.
function initialize(){
$("." + login).remove();
}
// this is a global function right now, use it anywhere you want.
function moreContent()
{
//more content is loaded
...
initialize();
}
// document ready...
$(function(){
moreContent();
});
You can rearrange the code and remove the unnecessary function layers (depends upon your code structure) and use it like this.
$(function(){
// more content...
initialize();
});
if I use a function like resize (in the end of the script.js file) it works
It worked because it is attached directly to window by jQuery on resize event.
$(window).resize(function(){
// The code inside will work whenever user resizes the window.
// It does not need to be hooked up inside document ready.
});
I have no idea why it suddenly works with the other function and why it doesnt work in the other cases
The reason it worked inside event handlers is because you hooked up your functions to run as a callback function to them. You have set it up correctly in click or resize event but not in load event. In load event you just created a function and added the it as a method to jQuery object but did not invoke it. The only and only way a function runs inside JavaScript is when you suffix parenthesis.
function demo()
{
// do something...
return "Done";
}
// a named function "demo" got created, but not invoked.
demo; // returns the whole function literal, not invoked yet.
demo(); // invoked, returns Done
So continuing from this, adding it as a method to jQuery will not load it, until you invoke it e.g.
jQuery.myNewMethod = function myNewMethod() {
return "Hey there :)";
}
// jQuery loaded, but where is my method ?? (#__#)
// let's invoke it then...
jQuery.myNewMethod(); // invoked the function using parenthesis!
// returns "Hey there :)"
// Now i can see you go (^__^)
$(document).ready(function () {
function EndSession() {
window.close();
};
setTimeout("EndSession()", 10000);
});
Shown above is the code in a child page opened using window.open().
The problem is after ten seconds when it tries to call EndSession, it throws an error
"Microsoft JScript runtime error: 'EndSession' is undefined"
What is going on here?
Maybe the problem of the old way "string" is that it was looking for the method in the global scope, while the method was defined inside the function used for jQuery ready.
We can explicitly pass the function we really want to, if we have a proper reference to it.
Let's try:
$(document).ready(function () {
var endSession = function() {
window.close();
};
setTimeout(endSession, 10000);
});
Although I haven't tried it, maybe even this will work:
$(document).ready(function () {
setTimeout(window.close, 10000);
});
I'm not sure if you need the jQuery ready at all too, unless you intentionally want to start counting time after the document is fully loaded (which I'd expect to be very quick for a pop-up that closes soon).
When the timeout event triggers, the code you specified is run in the global namespace.
Your code is "EndSession()", so the browser tries to find a global function with the name EndSession. There is no such function, because you defined EndSession() inside an anonymous function that you passed to $(document).ready().
So, defining EndSession as global will suffice.
function EndSession() {
window.close();
};
$(document).ready(function () {
setTimeout("EndSession()", 10000);
});
Also, functions that are not constructors should, by convention, start with lowercase letter ;)
that should be like this,
setTimeout(EndSession, 10000);
DEMO
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
Below is the code I am using in a project with some complex dependencies. After I have made sure that all the dependencies have been loaded I fire the onReadyCallback() also given below. I have two questions :
Is it correct to use, anonymousHandler.apply(MyNameSpace), the apply method on an anonymous Handler being called for Document.ready
From what I understand, because I am using the apply method the anonymous function will fire immediately irregardless of document's ready state. Then how can I pass in the context of MyNameSpace to the anonymousHandler so that "this" inside the function refers to MyNameSpace
var onReadyCallback = function(){
jQuery(document).ready(function(){
if(!this.loggedIn()){
return;
}
...Lots of Code referring to MyNameSpace using "this"
}.apply(MyNameSpace));
};
//load the additional files that are needed and fire onReadyCallback
MyNameSpace.Util.loadFiles(defaultJsFiles,function(){
MyNameSpace.Util.require(['My.App','My.Theme','My.DomHandler'], function(){
onReadyCallback.apply(window);
});
});
How about this, using an anonymous function and call?
jQuery(document).ready(function() {
(function() {
// this == MyNamespace
}).call(MyNamespace);
});
Normally, the ready event jQuery function is called like this
$(function() { /* ... */ });
// or
jQuery(function() { /* ... */ });
// or
jQuery(document).ready(function() { /* ... */ });
Bottom line, the function is not given a particular context; the actual context given by jQuery to the function is the HTMLDocument element, regardless of the argument (in the last example, document). Why is this so is another subject.
Generally, each of these functions are called later, after everything has been loaded, but not necessarily. In your case, there is a reference to MyNameSpace before the ready event happens. Even if Javascript is a LALR-type language, and it will find the symbol declared later, this is not a good practice. What if MyNameSpace would be set to something else later on, before jQuery triggers the ready callback functions? Your ready callback would not get that new reference. Unless intentional, the reference should be made inside the ready callback, when everything is.... ready.
Then, inside the ready callback, there are other techniques to assign a context to a function. lonesomeday have pretty much given the correct way to accomplish what you are trying to do.
(function() {
// this == MyNamespace
}).call(MyNamespace);
The above code executes an anonymous function right away, where this == MyNameSpace
note : the difference between apply and call is decribed here
Now, comes the bottom part of the code you provided :
//load the additional files that are needed and fire onReadyCallback
MyNameSpace.Util.loadFiles(defaultJsFiles,function(){
MyNameSpace.Util.require(['My.App','My.Theme','My.DomHandler'], function(){
onReadyCallback.apply(window);
});
});
This is problematic, and unnecessary. Is the function onReadyCallback only needed there, or will it be called several times? If it needs to be called only once, spare the global namespace, and simply do :
//load the additional files that are needed and fire onReadyCallback
MyNameSpace.Util.loadFiles(defaultJsFiles,function(){
MyNameSpace.Util.require(['My.App','My.Theme','My.DomHandler'], function(){
// if everything is done loading, the function will be executed, otherwise
// it's execution will be postponed later
jQuery(function() {
// create our nicely wrapped anonymous function now
(function() {
if(!this.loggedIn()){
return;
}
// ...Lots of Code referring to MyNameSpace using "this"
})(MyNameSpace); // grab our most recent reference of `MyNameSpace`
});
});
});
If you don't like the indentation (it's merely a developer's taste), replace everything in the ready callback with (something like) :
initMyNameSpace.apply(MyNameSpace);
and create your function outside, on the global space :
function initMyNameSpace() {
if(!this.loggedIn()){
return;
}
// ...Lots of Code referring to MyNameSpace using "this"
};
But I would recommand, at least, to put it in the require callback function so it...
...does not pollute the global namespace with a run-once function
...is not accessible from anywhere (keep it private)
...can be found quickly when editing the source code
etc.
note : usually, apply and call are used to avoid repeatedly accessing objects like some.thing.pretty.deep = value; or when one function needs to be applied to many but not all objects, and thus extending the object's prototype is just not a good idea.
This is my opinion anyway, and how I would do things, without any more knowledge of your code or what you are doing.