I understand when passing a function pointer to an event handler you cannot invoke the function block with parentheses or the return value of that function will be assigned to the event handler. I tried this and I'm confused on how it works?
window.onload = alert("Hello, World.");
I can see how this works:
window.onload = function () { alert("Hello, World!"); };
The literal function is not self-invoked leading to no return value and is only invoked once the onclick-event is invoked.
Edit 1: I don't want to achieve anything with this. I just want to understand how window.onload = alert("Hello, World."); works perfectly and how window.onload = show_message("Hello, World."); doesn't work?... Considering that show_message is actually a function.
Edit 2: Some user is claiming the onload event handler to work with parentheses on any function. I do not think this works like it should because the function is invoked ignoring the event handler and the return value of that function is assigned to the event handler. Most functions do not return anything so (undefined or null) will be assigned to the event handler.
Look at the code below:
var button = document.getElementById("button");
function test() {
str = "works";
console.log(str);
}
button.onclick = test;
Assume there is a button element with the id of button assigned to it. This will only work if test is not invoked with parentheses (button.onclick = test();). Test will only run once and undefined will be assigned to onclick.
Edit 3: It looks like a return value is not assigned to an event handler if the function is invoked. It always writes out null to the console when I use console.log.
Nice question. Actually it does not work as you expect it to work. It's just illusion that it works that way. When you run:
window.onload = alert("Hello, World.");
The right part of the statement is executed and alert is shown, but the window on load handler is not set up to some function, null will be assigned to it, since this is what alert returns.
By the way even if you call the method with parentheses you can return function from it to assign to the event handler:
var button = document.getElementById("button");
function test() {
str = "works";
console.log(str);
return function(){console.log('button clicked');}
}
button.onclick = test();
window.onload = alert("Hello, World.");, you saw the alert works just because it alert when it execute, and assign the result (undefined) to window.onload.
Related
I have written a piece of code. On clicking on a button corresponding function should be called. While the logic works for funcB and funcD i.e. they get invoked on clicking FieldB and FieldD. FunctionA gets called for some reason on page load.Can someone explain what am I doing wrong here?Happy to share additional code if doesn't make sense.
function funcA(array){alert("Invoked");}
function init() {
loadData();
document.getElementById("FieldA").onclick = funcA(array1);
document.getElementById("FieldB").onclick = funcB;
document.getElementById("FieldC").onclick = funcA(array2);
document.getElementById("FieldD").onclick = funcD;
}
window.onload = init;
When ever you call a function it returns a value. funcA(array1) doesn't refer to function variable but it will be the value returned from the function funcA which is undefined in this case. If you want to pass some arguments then use wrapper function.
document.getElementById("FieldA").onclick =() => funcA(array1);
A better way is to use addEventListener
document.getElementById("FieldA").addEventListener('click',e => funcA(array1))
you are executing the funcA on onload, instead you can add a wrapper function over the funcA eg:
document.getElementById("FieldA").onclick = function() {
funcA(array1);
}
I write some JavaScript code, when I write them in anonymous functions like
<br />"button.onclick = function() { some code; };,
It works normally. But when I try to write as
<br />
foe.onclick = myFunction();
function myFunction() { same code here; }
Then nothing happens when I click the button. I try to add alert in myFunction() and it appears immediately after the page is load. Why this happened?
You need to change from
foe.onclick = myFunction();
to
foe.onclick = myFunction;
When you use the function call with parentheses, you are calling the function. So, when you use:
foe.onclick = myFunction();
It actually executes the function at this point and returns the value for onclick to use.
You can also use:
function myFunction () {
return anotherFunction();
}
foe.onclick = myFunction();
Here, anotherFunction would be called when you click foe element.
As Xin points out, you can use:
foe.onclick = myFunction;
to call myFunction on clicking the element. In Javascript, functions can be referenced and passed like variables :D
Sorry if my question seems naive (a bit of a newbie here), but I seem not to be able to get a simple answer to my question.
In JavaScript I try something like this
window.onload = init; *// ok, this assigns to the window load event a function that doesn't execute straight away*
// now I define my init()function
function init(){
// say...
alert('Noise!');
/* but here is my dillema...
Next say I want to assign to an button.onclick event a function that only executes when I click the button.
But (!here it is...!) I want to pass arguments to this function from here without causing to execute because it (obviously) has brackets.
Something like: */
var button = document.getElementById('button');
var promptInput = prompt("Name?");
button.onclick = printName(promtInput); // I only want to print name on button click
}
function printName(name){
alert(name);
}
So... OK, I know the example is stupid. Simply moving all prompt gathering inside printName() function and assign to button.onclick a bracketless printName function will solve the problem. I know. But, still. Is there a way to pass args to functions you don't want to execute immediately? Or it really is a rule (or 'by definition') you only use functions that await execution when you don't plan to pass args via it?
Or how do you best to this thing otherwise?
Thanks a lot!
Ty
button.onclick = function() {
printName(promptInput);
};
You can use Function.prototype.bind():
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
For example:
button.onclick = printName.bind(null, promtInput);
You could put the data that you would normally pass as an argument into some other holding location. You can either put it in a hidden HTML element, or you can use the sessionStorage API to keep it. So your code would look like this:
var button = document.getElementById('button');
var promptInput = prompt("Name?");
sessionStorage.setItem('MyName', promptInput);
button.onclick = printName; // I only want to print name on button click
}
function printName(){
alert(sessionStorage.getItem('MyName');
}
window.onload = function() {
document.getElementById('clickMe').onclick = runTheExample;
}
function runTheExample() {
alert('running the example');
}
This is a simple event handler for the onclick event for an html input button with id = clickMe.
In line 2, why is the call to function runTheExample not immediately followed by ()? I thought that to call a function you must pass it any variables/objects it expects in an open/close parenthesis, and if the function isn't expecting anything, you must still include the open and close parenthesis like runTheExample().
document.getElementById('clickMe').onclick = runTheExample;
The intention here is not to call runTheExample() but to assign the reference to the function runTheExample to the onclick event.
Internally, when the onclick event is fired, Javascript is able to call the function runTheExample through the reference you provided on the code above.
Snippet
var myFunction = function() { return 42; };
// Assigning the reference
myObject.callback = myFunction;
myObject.callback(); // Has the same effect as calling myFunction();
// Assigning by calling the function
myObject.callback = myFunction();
myObject.callback; // Returns 42
myObject.callback(); // Exception! Cannot call "42();"
That's not Javascript-specific. Passing functions by reference is available in many languages.
You use the parenthesis only to invoke (call) a function. When you're assigning it to onclick, you're merely passing it by reference.
To better understand this, think about the other method of declaring a function:
var runTheExample = function () {
alert('running the example');
}
Regardless of what method you use, runTheExample will contain a reference to the function (there are some differences, like the function reference not being available before assignment, but that's a different story).
Functions are objects in javascript. That line sets the onclick property of the click me element to the runTheExample function, it doesn't call that function right then.
var a =runTheExample; //sets a to runTheExample
a(); //runs the runTheExample function
So when the function name is referenced without the () it is referring to the function object, when you add the () it is a call to the function, and the function executes.
It's not calling it, but rather setting the property onclick. When a call is made to onclick(), it will then run the function you've defined. Note however that the context of this will be the object that calls it (document.getElementById('clickMe')).
You're not calling the function here. You're setting the function as an event handler, and the function is not actually called called until the event is fired. What you've written references the function; that's a different notion than actually calling it.
In this case, the runTheExample function is being treated as a variable and being assigned to the onclick event handler. You use () after a function name to call a function. If you added them here, what would happen is that runTheExample() would be called once during load, showing an alert, and then a null value would be assigned to the onclick handler.
Because it binds runTheExample to onclick event.
When you add () it triggers the function.
This is the script that i tested when the page loads.
window.onload = initAll;
function initAll() {
document.getElementById("pTag").innerHTML = "Hello Java Script !";
}
The above script works fine till i put parenthesis like initAll() during the call. _( window.onload=initAll(); )_ . Nothing happens if use initAll() during function call. It is like the script wasn't there.
Why is it so ?
window.onload expects the value you set for it to be a function (functions are like any other object in JavaScript).
If you put parens after initAll, you actually invoke the function and set window.onload to the function's return value. Since the function does not return anything explicitly, this value is undefined. So in practice you can think of this code:
window.onload = initAll();
function initAll() {
// do something with document
}
as equivalent to this code:
var result = initAll();
window.onload = result;
function initAll() {
return null;
}
I 'm sure you can immediately see why this would not work.
Because you should not execute the function at that line, you should assign an event handler to the window object, which will be triggered/executed once the load event has fired, not the returned value of a function.
However, assigning an event handler window.onload is not recommended, because it will allow for only one handler to be attached. Consider using addEventListener.
Because you're not calling the function directly in the window.onload statement, but you're assigning a function to the onload event. The system will then automatically call your initall function when the event happens. Thats why you need the function itself (without parenthesis), and not the call (with parenthesis)
This has to do with the way Javascript works. Functions also are actually objects, like about everything in javascript.
So basically, you are assigning the "Object" initAll , which happens to be a function, to window.onload . This object is then called when the onload event is triggered, assuming it is a function.
Now, when you are putting parenthesis behind your objects name, you are basically telling it to treat that object like a function and call it. this is not the way how to assign it to a property, like the window.onload property.
window.onload = initAll;
You're binding the initAll function to the onload event of the window object. The function becomes the load handler. Now, when the load event fires at the window object, this function will be invoked.
window.onload = initAll();
You're immediately invoking the function initAll. this invocation returns undefined (in your case), and that undefined value will be assigned to window.onload. Assigning the undefined value to onevent properties obviously has no effect.
When you omit the parentheses in this call:
window.onload = initAll;
You are assigning to the window.onload event the reference value of the function initAll(). This causes the function to execute when the onload event is called because they share the same reference point. When you use the assignment like this:
window.onload = initAll();
You are assigning to the window.onload event the returned value of the function, which in this case is null.