Button doesn't work after I put them into named functions - javascript

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

Related

javascript onclick function executes on load

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

Why is alert is working only for a single time when not in function?

document.querySelector('html').onclick = function() {
alert('Hy');
}
works each time I click on the webpage displaying a dialogue box.
but if I were to remove function declaration and instead write
document.querySelector('html').onclick = alert('Hey');
it works only for once.
I don't understand this because I am asking javascript to alert by Hey each time I click on the webpage but it does the same only for once.
What effect does function declaration having on this snippet of code?
You need to distinguish between a function and the result of calling a function. In the second case, you're running the alert function immediately, and then setting the onclick to its result (which isn't a function and doesn't do anything useful).
Because what this does:
document.querySelector("html").onclick = alert("Hey");
It runs the code alert("Hey"), then sets the onclick of the element to the return value of alert("hey"). This will only work as a proper event handler if alert("Hey") returns a function. It doesn't:
console.log(alert("Hey"));
So you need to attach a function or function reference like so:
document.body.onclick = () => alert("Hey");
<p>Click Me</p>
The above works and is only a small addition to your wanted syntax - we're using ES6 arrow functions for this.

How to access function inside of function?

today my question is asking how I would access a function inside a function. So, for example, I have a button, and if I click it, it would alert. The thing is, if you have a function surrounding the function, the inside function with the alert would not alert.
Here's an example:
html:
<button onclick="doStuff()">Alert</button>
js:
function nothing() {
var doStuff = function() {
alert("This worked!")
}
}
so the doStuff() function would not work. Can someone help me find a way to access it?
#Joseph the Dreamer is ultimately correct, but if you were dead set on calling a function that's nested in another function you could use an OOP approach.
Create a javascript "class" object and scope your function to "this":
function Nothing() {
this.doStuff = function() {
alert("works");
}
}
Next you add an id to your button,
along with a click event listener
Then, inside your click event you can call doStuff within the Nothing "Class" function like this:
var object = new Nothing();
object.doStuff();
https://jsfiddle.net/me7fek5f/
You can't. That's because it's enclosed in a scope that you can't really access globally. The only way you can access it is to expose it somewhere outside nothing.
Is this a homework question?
You're probably asked to do something like this:
function nothing() {
var doStuff = function() {
alert("This worked!")
}
var yourButton = getYourButton();
attachClickListener(yourButton, doStuff);
The implementations of getYourButton and attachClickListener are left to the reader.

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.

What is wrong with this javascript code

In the code below, I have tried to display alert when the user clicks on the document.As I have done doAlert() with parenthesis, the code runs when the document load and alerts without any events occur but if I do simply
doAlert
It seems to respond when I click the document. So, is it must that I should call function in javascript without the parenthesis or what is the idea for doing this. What if I were to pass parameter to a function.
<!doctype html>
<html>
<head>
<script>
function doAlert(){
alert("Hello");
}
function init(){
document.onclick = doAlert();
}
window.onload = init();
</script>
</head>
<body>
</body>
</html>
If foo is a function, then bar = foo will assign that function to the variable bar, but bar = foo() will immediately call the function and assign its return value to bar instead.
Event handlers work by being given a function that will be called when the event happens. If you run the function immediately then its return value needs to be a function that you want to run when the event happens (in this case the return value of both doAlert and init is undefined).
document.onclick is being set to the return of doAlert and not the doAlert function itself.
Your code should look like:
<!doctype html>
<html>
<head>
<script>
function doAlert(){
alert("Hello");
}
function init(){
document.onclick = doAlert;
}
window.onload = init;
</script>
</head>
<body>
</body>
</html>
When you call a function, you get its return value.
window.onload = init();
This runs init() and sets window.onload to its return value, undefined.
You need to set it like this:
window.onload = init;
Now window.onload is set to the function init, it won't run until it needs to.
If you want to pass parameters, like in your onClick, you can do it like this:
document.onclick = function(){
doAlert('Clicked');
};
This sets onClick to an anonymous function, that calls the functions you want. Or, you can use a closure:
function doAlert(param){
return function(){
alert(param);
};
};
document.onClick = doAlert('Hello World');
doAlert is called, onClick is set to its return value, which is a function (in this case one that alerts 'Hello World').
Functions in Javascript are objects and can be passed along like any other variable. In your case, doAlert is just a reference to a function. In order to call the function pointed by this reference, you need to use parenthesis : doAlert().
The document.onclick method is supposed to be a function reference, so you assign it a function reference like this : document.onclick = doAlert. With your syntax, you assign the result of a call to doAlert() to document.onclick, which is incorrect.
Got it ? :)

Categories

Resources