This question already has answers here:
In JavaScript, does it make a difference if I call a function with parentheses?
(5 answers)
Closed 9 years ago.
Take the following code:
HTML
<button id="button>click me</button>
JS - VERSION 1
window.onload = init;
function init() {
console.log('init called');
var button = document.getElementById('button');
button.onclick = buttonClickHandler;
}
function buttonClickHandler() {
console.log('button clicked');
}
vs Same HTML
JS - VERSION 2
window.onload = init();
In both cases, 'init called' appears in the console "immediately", but in the second case, it is followed by an error stating button is null.
There are 2 things at play here. 1) In version 1, it waits for the DOM to load 2) in version 2, it's happening before the DOM is loaded, or so it seems.
My question. Please explain as clearly as possible what is happening in version 1 vs what is happening in version 2. What are the technical terms for what window.onload = init is vs what window.onload = init() is? Also please explain each versions behaviour. Why does 1 wait, but 2 doesn't?
The script needs to go before the button element e.g. in the head: http://jsfiddle.net/XMEjr/1/
Version 1 sets init function to be the one that's called on window.onload event. The function is not invoked on that line; it's just assigned (as a value) to a property.
Version 2 sets the result of init function to be the one that's called on window.onload event. It's the difference that () makes.
Apparently init function is called before onload is fired (to get that result and set it as onload handler). So the function starts, fails to find element by button id (as DOM is not ready yet), so getElementById returns null. Then trying to access onclick property of null stops it with an error.
in the second one you are assigning to onload the result of the call to init :)
It would be equivalent if you do:
window.onload="init()"
In this case you are assigning a String that gets evaluated upon DOM is ready.
If you do
window.onload=init
You are assigning a reference to a function. Then again, when DOM is ready, the function gets called
But if you do:
window.onload=init()
you could do
function init() { alert ("this is called before onload, dom is not ready, button doesnt exist"); return init2; }
function init2() { alert ("this is called on load, dom is ready, button and everything in the body is now created"); }
hope you get the point.
By the way, this case would be useful to do something like this:
window.onload=init()
function init() {
if (IS_IPHONE) return init_iphone;
if (IS_ANDROID) return init_android;
if (IS_WINDOWS) return init_not_supported;
}
so you select which init method to execute onload.
Related
I am having some problems with function declarations in IE. It appears, even if I link the function directly to the window object. I tried switching with document in stead of window, but with no success.
Here is the basic code that I am trying to use:
window.addEventListener('load', function () {
function initChart (id) {...}
//linking to window object
window.initChart = initChart;
});
As I said, I even tried to link it directly: window.initchart(id){...}. More that that, I even included the js file I declared the function inside the body(due to a rumor that says that IE doesn't see function declared in head section)
After that, inside script tags i call initChart() with a valid id and I get this error inside the IE console: 'initChart' is undefined.
<script>
initChart('chart');
</script>
The strange thing is that in Chrome, Firefox and Opera has no such problem. Any ideeas?
PS: If this is a duplicate, I did not found the question that covers this.
You also need to do initChart('chart'); inside of the window load event handler (this one or a later added one). Or you can do that in another event handler that you know for sure happens after this window load event handler.
As your code is processed by the browser, it knows to do something on the window load event, which is to set your window.initChart.
But then later on you are using it right away, without the event of window load happening yet.
If it doesn't happen in Chrome, I am wondering if everything is loaded, but even so, I'd think your window.initChart is set in the next event cycle. (let me try to do some experiments -- you are not doing any of these in the debugger but all inside an HTML file?). But it really shouldn't be ok in Chrome, because the load event handler doesn't occur before your <script> tag is parsed and executed, which does initChart('chart'); already.
But in any event, it is best to follow the event sequence: if you set window.initChart on window load event handler, then also only call window.initChart() in the same and later added event handler, or in an event handler that happens afterwards.
You can see in the following HERE 02 happens before HERE 01:
window.addEventListener('load', function() {
console.log("HERE 01");
});
console.log("HERE 02");
I am running the following in Chrome and I did get an error as expected:
window.addEventListener('load', function() {
function foo() {
console.log("HERE 01");
}
window.foo = foo;
});
foo();
But this one worked as expected:
window.addEventListener('load', function() {
function foo() {
console.log("HERE 01");
}
window.foo = foo;
});
window.addEventListener('load', function() {
foo();
});
The problem apparently was not the linkage between the function and the window object. In my load event I had some ES6 string interpolation(something like this: console.log(`#${id}`)) and IE falls short on this. He doesn't know what to do with it. So as a consequence, my window.initChart() was not even compiled. After I commented the code in matter, my initChart function was working fine. Thanks for help tho, #nopole!
This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Closed 7 years ago.
When we are doing inline command in the button:
<button id="myButton" onclick="alert('Hi!')">
Why does
document.getElementById("myButton").onclick = alert('Hi!')
not work but give the alert as the page is loaded? I can't understand how it works with function() added to it and without function(). I hope you guys understand my question. I'm missing something here.
document.getElementById("myButton").onclick = alert('Hi!')
is wrong since onclick should be assigned to a function reference, not the function call result itself.
It will execute alert('Hi!') when the page is loaded but that is not the intention here, is it? The intention behind assigning an onclick handler is to ensure that when the button is clicked this alert will be executed.
For that to happen it should be:
document.getElementById("myButton").onclick = function(){alert('Hi!')};
Also, this will not work unless it is wrapped inside the window.onload event:
window.onload = function(){
document.getElementById("myButton").onclick = function(){alert('Hi!')};
};
alert('Hi!') is a function call that alerts 'Hi' and returns nothing (undefined).
onclick expects to get a function and you are passing the function call's result which is undefined.
Since JavaScript is not a strong typed framework you don't get an error on bad assignments.
So why does the following work:
<button id = "myButton" onclick="alert('Hi!')">
It's because the html parser (in this case, your browser) does some work behind the scenes and wraps the call with a function.
document.getElementById("myButton").onclick expects a function to be called later.
<button id = "myButton "onclick="alert('Hi!')"> expects a block of code to be executed later.
alert('Hi')
Here alert is an inbuilt function called by browser which opens a alert box.
function callAlert(){
alert('Hi');
}
Here callAlert is a custom function which calls the inbuilt function alert
In your example, when appending a click event, you have to define the function
document.getElementById("myButton").onclick = alert('Hi!') //alert is
already executed
document.getElementById("myButton").onclick = function (){ alert('Hi!') };
//a function is defined/declared which will be executed when the onclick action is performed
See this post for explanation for why the inline version works.
In short, the browser doesn't just assign alert('Hi!') to onclick but instead wraps it in a function.
This question already has answers here:
Why does click event handler fire immediately upon page load?
(4 answers)
Closed 6 years ago.
var season = "10";
$( document ).ready(function() {
$("#table").hide();
});
$('#searchButton').on("click", showTable(event));
function showTable(event){
$("#table").show();
document.getElementById("td").innerHTML = season;
}
How is it possible, that the function showTable(event) is automatically executed when the page is loaded?
Another problem is, that the click event doesn't work if the button is clicked.
What did I do wrong?
How is it possible, that the function showTable(event) is automatically executed when the page is loaded?
Because you are calling the function: showTable(event). () after a function reference means to execute the function. You are calling showTable and passing the return value (undefined) to .on().
Here is a simplified example:
function foo() {
return 42;
}
function bar(x) {
console.log(x);
}
bar(foo());
This calls the function foo, and passes its return value (42) to bar, which in turn logs the value.
If we'd write bar(foo) instead, we'd pass the function itself and bar could execute the function.
What did I do wrong?
You are calling the function. Pass it to .on instead and let the browser call it:
$('#searchButton').on("click", showTable);
The line:
$('#searchButton').on("click", showTable(event));
Actually executes showTable(event). What you want is:
$('#searchButton').on("click", showTable);
Why?
When you have $('#searchButton').on("click", showTable(event));, what is sent to the .on() is the result of the showTable(event) function execution.
If you use $('#searchButton').on("click", showTable);, what you send as second argument to the .on() function now is a reference to the showTable function, not its result.
By saying showTable(event), you are invoking the function.
What you need to do is this:
$('#searchButton').on("click", function (event) {
showTable(event)
});
This question already has answers here:
What is the difference between a function call and function reference?
(6 answers)
Closed 7 years ago.
When we are doing inline command in the button:
<button id="myButton" onclick="alert('Hi!')">
Why does
document.getElementById("myButton").onclick = alert('Hi!')
not work but give the alert as the page is loaded? I can't understand how it works with function() added to it and without function(). I hope you guys understand my question. I'm missing something here.
document.getElementById("myButton").onclick = alert('Hi!')
is wrong since onclick should be assigned to a function reference, not the function call result itself.
It will execute alert('Hi!') when the page is loaded but that is not the intention here, is it? The intention behind assigning an onclick handler is to ensure that when the button is clicked this alert will be executed.
For that to happen it should be:
document.getElementById("myButton").onclick = function(){alert('Hi!')};
Also, this will not work unless it is wrapped inside the window.onload event:
window.onload = function(){
document.getElementById("myButton").onclick = function(){alert('Hi!')};
};
alert('Hi!') is a function call that alerts 'Hi' and returns nothing (undefined).
onclick expects to get a function and you are passing the function call's result which is undefined.
Since JavaScript is not a strong typed framework you don't get an error on bad assignments.
So why does the following work:
<button id = "myButton" onclick="alert('Hi!')">
It's because the html parser (in this case, your browser) does some work behind the scenes and wraps the call with a function.
document.getElementById("myButton").onclick expects a function to be called later.
<button id = "myButton "onclick="alert('Hi!')"> expects a block of code to be executed later.
alert('Hi')
Here alert is an inbuilt function called by browser which opens a alert box.
function callAlert(){
alert('Hi');
}
Here callAlert is a custom function which calls the inbuilt function alert
In your example, when appending a click event, you have to define the function
document.getElementById("myButton").onclick = alert('Hi!') //alert is
already executed
document.getElementById("myButton").onclick = function (){ alert('Hi!') };
//a function is defined/declared which will be executed when the onclick action is performed
See this post for explanation for why the inline version works.
In short, the browser doesn't just assign alert('Hi!') to onclick but instead wraps it in a function.
Sorry if this may be deemed a slight duplicate, however I couldn't find an answer that helped me understand why myFunc() is firing on page load and not when I click el1 or el2. How can I make the following code behave as expected?
function myFunc(param){
//yadayada
}
el1.onclick = myFunc('string1');
el2.onclick = myFunc('string2');
Thanks.
document.getElementById('el1').onclick = function() { myFunc('string1'); };
document.getElementById('el2').onclick = function() { myFunc('string2'); };
You need to get the elements on the page first and then assign a function to them, otherwise the parser will execute them onload because it thinks that myFunc() is returning a value to be assigned to onclick as opposed to the actual function myFunc().