javascript onclick function executes on load - javascript

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);
}

Related

Detect the caller and called it

I want to recognize the calling function and one function call it that
The following example illustrates this issue
<script>
var func = (function () {
var check = function (value) {
//detect caller function
var that = arguments.callee.caller;
//I want
//if Buttom One click --> call print in func1
//if Buttom Two click --> call print in func2
};
return {
check:check
}
})();
var func1 = (function () {
var start = function () {
func.check(10);
};
var print = function (value) {
alert(value);
}
return {
start: start,
print: print
}
})();
var func2 ...
</script>
<button id="One" onclick="func1.start()">One</button>
<button id="Two" onclick="func2.start()">Two</button>
Do you have a solution?
Many thanks!
Putting aside the fact that arguments.callee and Function.caller are both non-standard, the reason why it doesn't work is that you are confusing properties with local variables, all that mixed in with closures.
var func1 = (function () {
// ...
})();
This creates a function, runs it and saves the result in func1. Since the return statement of your closure is return { start: start }, at the end of this section of code func1 will contain an object which as a method called start.
When you use var, you're only creating a variable which exists inside that function. Outside of the function, it is no longer accessible. You did store the start function in the returned object, but you never returned print so it doesn't exist anymore.
Instead of going line by line and trying to explain all what is wrong, I'll ask you this: what you were actually trying to do? Don't ask us about your attempted solution which didn't work, but about what the code should do.
I suggest you look at these answers I wrote if you need further explanations on closures and scope.
Understanding public/private instance variables
Do the different methods of creating classes in Javascript have names and what are they?

onclick assigned function with parameters

I'm not sure if this has been asked before because I don't know what it's called.
But why wouldn't a method like this work? Below is just a general example
<script>
document.getElementById('main_div').onclick=clickie(argument1,argument2);
function clickie(parameter1,parameter2){
//code here
}
</script>
The code above would work fine if the event handler was assigned without parameters, but with parameters, it doesn't work. I think I read online that to overcome this problem, you could use closures. I'm assuming it's because of the parentheses ( ) that is calling the function immediately instead of assigning it to the event?
Because you're calling the function immediately and returning the result, not referencing it.
When adding the parenthesis you call the function and pass the result back to onclick
document.getElementById('main_div').onclick = clickie(); // returns undefined
so it's actually equal to writing
document.getElementById('main_div').onclick = undefined;
which is not what you want, you want
document.getElementById('main_div').onclick = clickie;
but then you can't pass arguments, so to do that you could use an anonymous function as well
document.getElementById('main_div').onclick = function() {
clickie(argument1,argument2);
}
or use bind
document.getElementById('main_div').onclick = yourFunc.bind(this, [argument1, argument2]);
It is however generally better to use addEventListener to attach event listeners, but the same principle applies, it's either (without arguments)
document.getElementById('main_div').addEventListener('click', clickie, false);
or bind or the anonymous function to pass arguments etc.
document.getElementById('main_div').addEventListener('click', function() {
clickie(argument1,argument2);
}, false);
The easiest way is:
yourElement.onclick = yourFunc.bind(this, [arg1, arg2]);
function yourFunc (args, event) {
// here you can work with you array of the arguments 'args'
}
When you say onClick = function() {...} you are registering your function with some internal JavaScript library. So when the "click" happens, that library invokes your function.
Now imagine you're the author of that library and someone registered their function with it. How would you know how many parameters to pass to the function? How would you know know what kind of parameters to pass in?
clickie(argument1,argument2)
This means to invoke the function and return its return value.
clickie
This simply is a reference to the function (doesn't invoke/execute it)
To bind an event to a element, you need to use either the attachEvent or addEventListener method. For example.
/* Non IE*/
document.getElementById('main_div').addEventListener('click', function () {}, false);
/* IE */
document.getElementById('main_div').attachEvent('onclick', function () {});
A function name followed by parentheses is interpreted as a function call or the start of a function declaration. The a onclick property needs to be set to a function object. A function declaration is a statement, and is not itself a function. It doesn't return a reference to the function. Instead it has the side effect of creating a variable in the global scope that refers to a new function object.
function clickie(param) { return true; }
creates a global variable named clickie that refers to a function object. One could then assign that object as an event handler like so: element.onclick = clickie;. An anonymous function declaration (often confused with a closure; for the difference see Closure vs Anonymous function (difference?)) does return a function object and can be assigned to a property as an event handler, as follows:
element.onclick = function(event) { return true; };
But this doesn't work:
element.onclick = function clickie(event) { return true;};
Why? Because function clickie(event) { return true;} is a statement, not a function. It doesn't return anything. So there is nothing to be assigned to the onclick property. Hope this helps.

Passing argument to function I don't want to execute immediately

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');
}

Why does a Javascript function call not contain '()' after the name of the function?

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.

Passing a function pointer to an event in JavaScript

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.

Categories

Resources