does var onload mean that it should run when page is loaded - javascript

// test.js //
var testObj = {};
testObj.init = function(){
console.log('google');
}
var onload = testObj.init;
/// what does it mean, does it mean it gets executed when script loaded or what, I just can't understand it as it is not looging into console anything under Google Chrome plugin...

Think of it like giving your dog 2 names:
var spot = new Dog();
var comeHereSpot = function () { return spot; }
var comeHereBoy = comeHereSpot;
Whether you call comeHereSpot or comeHereBoy the same dog will come running.

It just means that your variable onload now points to
function(){
console.log('google');
}
onload is just the name of a local variable here.

It means that variable onload is a reference to the function testObj.init. onload() will execute the function and output 'google' to the console.

No, it only means that you assign it to a variable named onload.
Depending on the scope of the code it might actually work, if the variable name collides with the onload property of the window object. In that case a variable would not be created, but it would use the existing property instead. You should not rely on this behaviour though, you should always specify it as a property of the object:
window.onload = testObj.init;

In your code, onload is simply the name of a local variable. The var keyword declares local variables. You're setting the value of onload to testObj.init, which is a function that prints 'google' to the console.
To make it run the function on page load, set window.onload to the value of the function.
window.onload = testObj.init;
Or, better yet, use event handlers to attach an "onload" event to the window object. (To make this easier, use a JavaScript library such as jQuery, but I recommend you first learn how it all works.)

Nothing is logged because you are simply setting onload to be a pointer to the function testObj.init which only gets the function's code. To actually run it, you must call testObj.init().
More about onload…
onload is a property of an HTML element that can be set to run javascript. For example:
<html>…
… <body onload="testObj.init()"> …
…</html>
This means that when the "body" element is loaded, the function testObj.init() is run.
The "onload" property can also be attatched by javascript, as in:
window.onload=myFunction();

Related

When/Why does a Browser Implement Code

Why does this work,
function gettingValue() {
var holder = document.getElementById("testing").value;
document.getElementById("displayer").innerHTML = holder;
}
When the following doesn’t?
var holder = document.getElementById("testing").value;
function gettingValue(holder) {
document.getElementById("displayer").innerHTML = holder;
}
The language is Javascript, I was using Microsoft Edge and Opera browsers.
My guess is that the browser doesn’t perform code unless prompted. So var holder = document.getElementById(“testing”).value gets run in the first example because the function that contains it is called by a button.
When var holder = document.getElementById(“testing”).value is put inside a block of script with nothing ‘prompting’ it using the value holder returns undefined. Replaceing document.getElementById(“testing”) with a string “Blue” doesn’t work either. If a function calls holder the value returned is still undefined. So the browser did not create a varable.
I tried having the js document have;
function gettingValue(holder) {
document.getElementById("displayer").innerHTML = holder;
}
And passing the reference document.getElementById(“testing”).value to holder through the HTML document. It didn’t work, the function wasn’t even called because displayer stayed at Default instead of changing to undefined.
Oh experts of stackoverflow, please summarize how and when a browser reads/performs code.
//I realize this might be a 'discussion' which the tutorial said to avoid, if so I apologize. Tell me if this is so and I will not do it again.
Your guess is right - the variable definitions are run as soon as they are executed by the browser, so
var holder = document.getElementById("testing").value; is going to execute that instruction immediately, regardless whether the DOM structure is ready, since it's in outter-most scope. It all depends on where the code is placed in relation to the application entry point and runtime status.
This can obviously be correct, if that variable is defined in a correct place. Function body will only be executed when the containing function is called. It just 'sits' there, and until it is called, the only concern of the browser is if that code is syntactically correct(conforms to JavaScript specification syntax), i.e. can be parsed.
Your problem doesn't appear to have anything to do with when code is executed.
var holder = document.getElementById("testing").value;
The above defines a variable called holder. It is a global because it is outside of any function.
function gettingValue(holder) {
The function also defines a variable called holder by specifying it as an argument name. This variable is scoped to the function.
When you try to access the variable holder, you access the one in the nearest scope.
That's the argument to the function and not the global.
If you didn't mask it:
function gettingValue() {
Then you would be able to access the global.
Your question is very much about when code executes.
Let's look at each thing you tried. First
function gettingValue() {
var holder = document.getElementById("testing").value;
document.getElementById("displayer").innerHTML = holder;
}
That just tells the browser to create a function that is defined by that code in it. It really does not execute the contents of that function, just defines the function. In order for that function to get executed, you have to have some event or some other piece of code, that is executing, call that function. The call to that function, from some event (like a button press) or from other code, tells it to execute.
Now on your second attempt...
var holder = document.getElementById("testing").value;
function gettingValue(holder) {
document.getElementById("displayer").innerHTML = holder;
}
That first line of code is outside of any function definition and it will probably execute when the page loads. That holder variable DOES get created, and it has global scope, which means any function can access it. But, since you don't event have it inside a document_ready event handler, that "testing" control is probably still undefined (the page is not fully loaded when that statement executes) so you get undefined for the contents of "testing".
For your last example, it is hard to say what is going on without seeing the html that had those "testing" and "displayer" controls.
Bottom line, code gets executed when something calls it. When you load a page, any code that is outside of function declarations, executes and has global scope. Anything defined in a function gets executed when that function is called, either by an event or other code.
The issue with the code in the example is an issue with scope:
Your second example doesn't work as expected because you're referencing two different variables/pointers.
var holder = document.getElementById("testing").value;
function gettingValue(holder) {
document.getElementById("displayer").innerHTML = holder;
}
The following scope tree should explain this better:
GLOBAL SCOPE:
defined `holder` (through `var`)
gettingValue SCOPE
defined `holder` (as parameter)
Because you're defining holder as a parameter for gettingValue, you're no longer able to reference the global scope variable inside of gettingValue because they have the same name.
Specifying a parameter in a function definition is very similar to simply defining that variable within the function itself:
var holder = document.getElementById("testing").value;
function gettingValue(holder) {
document.getElementById("displayer").innerHTML = holder;
}
Is equivalent to:
var holder = document.getElementById("testing").value;
function gettingValue(firstParameter) {
var holder = firstParameter;
document.getElementById("displayer").innerHTML = holder;
}
Instead, you may have success doing one of the following:
function gettingValue(value) {
document.getElementById("displayer").innerHTML = value;
}
var holder = document.getElementById("testing").value;
gettingValue(holder);
OR
function gettingValue() {
var holder = document.getElementById("testing").value;
document.getElementById("displayer").innerHTML = holder;
}
gettingValue();
Notice in both examples above we have to call the function in order to execute it (using gettingValue()).
I hope this helps!
As a side note, Scotch.io has a great article that explains how scope works in JavaScript: https://scotch.io/tutorials/understanding-scope-in-javascript
Alright ; I had two misconceptions that were tripping me up.
I was assuming a local variable (used inside function) would be the same as a global variable if they had the same name. //Now that I realize that was the problem I remember reading about it.
I had thought document.getElementById(“blah”).value would be read from the ’s value every time it was used. This is not true, it is read only once when it is a global varable. As a local varable it is ‘read’ to whenever the function containing it is called.
I was blindsided by;
Global variables in javascript are read before the HTML document puts values into its elements. So that was why var holder = “Blue” returned “Blue” when var holder = document.getElementById(“testing”).value returned undefined. It was an order of operations thing. A value had not been put into the element yet. So my lesson is not to use document.getElement... in global variables.
Thank you all for your time and attention.

Why variable appears undefined outside document ready tags

I have observed a strange behavior while learning jQuery and Javascript. When I call a variable that is defined inside the $(document).ready, from outside these tags it appears undefined, even when I define it as a global variable,
For example:
$(document).ready(function() {
myVar = "test";
});
alert(typeof(myVar));
//Results "undefined"
If I call the same variable inside the document.ready tags it works as expected
$(document).ready(function() {
myVar = "test";
alert(typeof(myVar));
//Results "String"
});
The result is same even after using window prefix.
$(document).ready(function() {
window.myVar = "test";
});
alert(typeof(window.myVar));
//Results "undefined"
I understand about the variable scopes but why even global variables aren't working this way. I am so confused.
The code inside the "ready" handler will not run until the DOM has been fully built. The code outside the handler will run as soon as it is encountered. Thus, your alert() runs before the code in the handler runs, so the outcome makes perfect sense: the global variable has not yet been initialized, so its value is undefined.
You can see the sequence of execution clearly by putting alert() (or, better, console.log()) calls inside the "ready" handler:
$(document).ready(function() {
console.log("In the 'ready' handler");
});
console.log("Outside the 'ready' handler");
When that runs, you'll see the "Outside" message logged first.
Because the alert() is executed before your document is perfectly ready.. You may try even by declaring the variable before $(document).ready() still it will return undefined..
The $(document).ready() gets fired after the page is fully loaded
When the script tag is fully loaded the alert gets executed.
So
Script tag is loaded => Execute alert
Continue loading page
Page completly loaded => fire $(document).ready
You var is getting set
The alert gets executed before your var is set
The other answers are correct but it is probably important to also note the $(document).ready(...) is also hiding your variable from the global scope. You could declare your variable then update it within the function
var myVar;
$(document).ready(function() {
myVar = "test";
});
console.log(myVar) // test
The execution plan it's like
//this statement shall fix the driver, not run it
$(document).ready(function() {//-->this it's an event handler waiting to be fired when content is fully loaded
myVar = "test";//-->myVar won't exists until this event is triggered
});
//this execute the alert function but myVar not exist yet
alert(typeof(myVar));
$(document).ready() is like to assign an event who will execute after the content is loaded, which means alert(myVar) will run before the lambda execution which was set as the content-loaded event. I hope you'll understand me.

how to access a local javascript var in greasemonkey

it's been an hour I'm going crazy with this problem.
There is a page, with a javascript function:
<script>
function foofunction(foo){
dosomething(foo);
}
</script>
I have replaced this function with a greasemonkey script:
var scriptCode = new Array();
scriptCode.push('function foofunction(foo){ ');
scriptCode.push(' dosomething(foo); ');
scriptCode.push(' myinjectedcode; ');
scriptCode.push('}' );
var script = document.createElement('script');
script.innerHTML = scriptCode.join('\n');
scriptCode.length = 0;
document.getElementsByTagName('head')[0].appendChild(script);
//here I have to access to foo value
This works.
Now I have to access to foo value in my greasemonkey script, how can I?
Why are you making your JavaScript function inside a array? I'm assuming foofunction is a global function, why don't you just make a function inside window (or unsafeWindow, I think, for Greasemonkey)?
unsafeWindow.foofunction = function(foo){
dosomething(foo);
//myinjectedcode;
}
foo is a local variable, so it only exists inside the foofunction function. If you want access to it outside of that, you'd need to make it a global variable.
unsafeWindow.foofunction = function(foo){
dosomething(foo);
//myinjectedcode;
unsafeWindow.myFoo = foo;
}
unsafeWindow.myFoo; // will be set to `foo`, but only after `fooFunction` is ran
Problem with that is, myFoo will only be set after fooFunction is ran, and there's no good way for you to wait until then. I suggest making a "callback" function.
unsafeWindow.foofunction = function(foo){
dosomething(foo);
//myinjectedcode;
unsafeWindow.myFooCallback(foo);
}
unsafeWindow.myFooCallback(foo){
// this will be called with `foo` after `fooFunction` is ran.
}
But, this is kinda pointless as your injecting code into fooFunction anyway.
So, to answer your question, you cannot get the value of a local variable outside of the function. Since you're injecting code anyway, why don't you just put all code relating to foo inside fooFunction?
If what you are trying to do is keeping trace off the value in the process I recommend using Firebug to debug this type off scripts, just put a breakpoint anywhere you want in your script and at the time it stops it will give you the current values off all the variables being use.

Javascript wont run correctly

http://jsfiddle.net/NCt4D/
I want it to move (the image is large), but it dont work.
Firebug says reference scrollDivDown is not defined, but it's there?
It's JS fiddle.
Under "Choose framework", select "no wrap (body)". This prints your code at the end of your content and not wrapped in a function. This is what you would normally/ideally do to a script, which is load them after content, but before the body closes.
and like what the #jcomeau_ictx said, event handlers don't need the (). they just require the name (technically, the reference of) the function you want to execute. additionally, if you want to execute more functions on load, than just scrollDivDown, you can do:
window.onload = function(){
scrollDivDown();
foo();
bar();
baz();
}
also, prepend the subject of your handler (in this case, window) before the onload. although the subject is implied as window in the global scope, just prepend it to avoid confusion. It's also best practice to do so as well.
http://jsfiddle.net/NCt4D/1/
scrollDivDown was inside a closure and therefore was not accessible in the global scope where the timeout was executing in.
window.onload = scrollDivDown; // do not append ()

What's the correct way to call JavaScript Function?

In the following code, the function writeMessage is called without parenthesis. However it works fine but Is it a correct way of function calling in javaScript or its better to use parenthesis along with writeMessage().
window.onload = writeMessage;
function writeMessage()
{
document.write("Hello World");
}
window.onload = writeMessage; is not a call - it's an assignment. You assign the writeMessage function as the onload field of the window object. The actual call is performed (internally) as window.onload() which is equivalent to writeMessage() in your case.
In the following code, the function writeMessage is called without parenthesis.
Actually, it isn't. The code
window.onload = writeMessage;
does not call the function. It assigns the function to the onload property of window. Part of the process of loading the page in browsers is to fire the function assigned to that property (if any) once the loading process is complete.
If you wrote
window.onload = writeMessage();
what you'd be doing is calling writeMessage and assigning the result of the call to window.onload, just like x = foo();.
Note that the code you've actually quoted, which executes a document.write when the page loads, will wipe out the page that just loaded and replace it with the text "Hello world", because when you call document.write after the page load is complete, it implies document.open, which clears the page. (Try it here; source code here.) In modern web pages and apps, you almost never use document.write, but in the rare cases where you do, it must be in code that runs as the page is being loaded (e.g., not later).
the () is used to EXECUTE the function
when you write
window.onload = writeMessage;
you actually set a delegate ( pointer to a function to be executed) for which - when the onload event will occour.
That's correct already.
You don't need parenthesis because you're just storing the function in window.onload, not calling it yourself.

Categories