Simple question about using functions and invoking them - javascript

Pretty basic question, but I'm not able to find a suitable answer anywhere as I'm not sure what verbiage to use. I'm trying to better understand what is happening here so I can keep myself from making this mistake again. As you can see on the last line, I'm trying to set the onclick event, but it immediately invokes the function. The solution is to remove the parenthesis, but what exactly is that doing? What is the difference between the two? Thanks for any help.
let element = document.querySelector("button");
function turnButtonRed (){
element.style.backgroundColor = "red";
element.style.color = "white";
element.innerHTML = "Red Button";
}
element.onclick = turnButtonRed();

think of turnButtonRed as a variable.
var turnButtonRed = function(){ return 2 };
Now, if you use that variable to pass it to onclick, for example, you have 2 possibilities
element.onclick = turnButtonRed; // this is setting onclick to a function
element.onclick = turnButtonRed(); // this is setting onclick to whatever the function returns (2 in this case).
You want onclick to be set to a function, not the result of a function. turnButtonRed() gives you the result of the function, turnButtonRed is the function itself.

In the statement element.onclick = turnButtonRed(); you are assigning the result of calling turnButtonRed, not that function itself. Simply remove the ().
Here is why. I refer you to the mighty Table of Operator Precedence!
Your line of code has two operators, assignment and function call. Let's see:
Function call is 20
Assignment is 3
We do things in operator precedence order, from highest to lowest. So what is happening is, you are evaluating the function call turnButtonRed() first, then assigning that result to the handler. Which isn't what you want.
Just remove the function call, and assign the function:
element.onclick = turnButtonRed;
Here, we are not calling the function. Instead we assign the function itself as an event handler.
Now, the preferred, modern way of doing this is to add an event handler:
element.addEventListener("click", turnButtonRed);
I leave it as an exercise to the reader to explore why this might be preferred.

Related

My chrome extension change itself background not my web page background? [duplicate]

I have the following function
function hello() {
alert("hi!");
}
Take this piece of code:
var elem = document.getElementById("btn");
elem.onclick = hello;
My question might be a bit hard to understand, so bear with me:
What EXACTLY differentiates THIS piece of code from a normal call, or what makes this piece of code require a reference to the function variable rather than a regular call? (hello();)
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Well, the onclick property expects a reference to a function, for it to execute when the element is clicked. Normally it's either:
element.onclick = funcRef;
or
element.onclick = function () {
funcRef();
};
(but of course, it's best to use addEventListener and attachEvent)
Notice how both of them are references to functions, not calling.
When something expects a reference, you don't call it...you assign a reference to it (first example).
When you want to specifically call a function, you call it with () (second example). But notice how in the second example, there's still a reference to a function that's assigned to onclick - it's just an anonymous function.
Probably the more important part:
Some people think you want to do this:
element.onclick = funcRef();
But that immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn't what you want.
I think the moral of the story is that when you want/need something to execute right now, you call the function. If the function is wanted for later use or needs stored, you don't call it.
Do you want it to execute NOW? Then call it.
a=hello() means "Call hello() ASAP, and set its return value to a".
On the other hand, a=hello means "a is an alias for hello. If you call a(), you get the same results as calling hello()"
You use the latter for callbacks, etc, where you want to tell the browser what you want to happen after an event occurs. For example, you may want to say "call hello() when the user clicks" (as in the example). Or, "When the AJAX query returns a result, call the callback() function on the returned data".
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Do you need the function to run now?
Than add the () to execute it
Do you need to function to be referenced so it is called later?
Do not add the ().
Pretty much all statements in JavaScript have a return value. Unless otherwise specified, functions in JavaScript will return undefined when called. So, the only context in which it would make sense to call your function in this assignment statement if it were to return a function:
function hello() {
return function() {
alert("hi!");
}
}
elem.onclick = hello();
A reference to your function is needed somewhere no matter how it gets called. The difference here is that you are not explicitly calling the hello function. You are assigning a reference to that function to the elem DOM node's onclick event handler so that when onclick is fired for that Node, your function gets called.
hello() means you call that function, which means the function will be executed directly.
while when you have elem.onclick = hello, this is called a callback. Where hello doesn't get executed directly but only when a certain event is fired (in this case when there's a click on the element)

What is the Difference between function and function() When I call them in javascript?

I had a question before and a person answered it very well, My code works now, But I didn't completely understand the answer. This is the coding bit that I didn't understand -
document.getElementById("myButton").onclick = words;
Now I already had defined function words(). My mistake was that I had written words() instead of words. So what is the difference between calling of words() and words ?
words evaluates as a function.
words() calls that function and evaluates as the resulting return value.
The value you assign to onclick needs to be the function you want to get called when the click happens.
If you want the words function to be called, you have to assign that.
The difference between words and words() is that in the first case you are referencing the function and in the second case you are calling it
so when you do
document.getElementById("myButton").onclick = words;
you are assigning a function words to the onclick listener, while if you do
document.getElementById("myButton").onclick = words();
you are actually assigning the evaluated value of words to the onclick listener. onclick needs to be assigned a function which will be called when an onclick event happens.
Doing:
document.getElementById("myButton").onclick = words;
this means:
put a pointer to the function and when the event fires it will call the function. When you do words() you call the function.

javascript setInterval(tick(), 1000) [duplicate]

I have the following function
function hello() {
alert("hi!");
}
Take this piece of code:
var elem = document.getElementById("btn");
elem.onclick = hello;
My question might be a bit hard to understand, so bear with me:
What EXACTLY differentiates THIS piece of code from a normal call, or what makes this piece of code require a reference to the function variable rather than a regular call? (hello();)
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Well, the onclick property expects a reference to a function, for it to execute when the element is clicked. Normally it's either:
element.onclick = funcRef;
or
element.onclick = function () {
funcRef();
};
(but of course, it's best to use addEventListener and attachEvent)
Notice how both of them are references to functions, not calling.
When something expects a reference, you don't call it...you assign a reference to it (first example).
When you want to specifically call a function, you call it with () (second example). But notice how in the second example, there's still a reference to a function that's assigned to onclick - it's just an anonymous function.
Probably the more important part:
Some people think you want to do this:
element.onclick = funcRef();
But that immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn't what you want.
I think the moral of the story is that when you want/need something to execute right now, you call the function. If the function is wanted for later use or needs stored, you don't call it.
Do you want it to execute NOW? Then call it.
a=hello() means "Call hello() ASAP, and set its return value to a".
On the other hand, a=hello means "a is an alias for hello. If you call a(), you get the same results as calling hello()"
You use the latter for callbacks, etc, where you want to tell the browser what you want to happen after an event occurs. For example, you may want to say "call hello() when the user clicks" (as in the example). Or, "When the AJAX query returns a result, call the callback() function on the returned data".
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Do you need the function to run now?
Than add the () to execute it
Do you need to function to be referenced so it is called later?
Do not add the ().
Pretty much all statements in JavaScript have a return value. Unless otherwise specified, functions in JavaScript will return undefined when called. So, the only context in which it would make sense to call your function in this assignment statement if it were to return a function:
function hello() {
return function() {
alert("hi!");
}
}
elem.onclick = hello();
A reference to your function is needed somewhere no matter how it gets called. The difference here is that you are not explicitly calling the hello function. You are assigning a reference to that function to the elem DOM node's onclick event handler so that when onclick is fired for that Node, your function gets called.
hello() means you call that function, which means the function will be executed directly.
while when you have elem.onclick = hello, this is called a callback. Where hello doesn't get executed directly but only when a certain event is fired (in this case when there's a click on the element)

JavaScript - added function to onclick attribute of <a> runs without click

I have a function that creates a new <a> element and I want to add a onclick event to it, which is a function that increases the given value by 1.
In the function, I create these elements:
A number within spantags:
var spantags = document.createElement("span");
var anzahl = 1;
spantags.innerHTML = anzahl;
And the mentioned <a> element:
var plus = document.createElement("a");
plus.innerHTML = "+";
plus.onclick = more(spantags.innerHTML);
This, however, executed the function already in the function that creates this, so the number was increased to 2 on creation.
I read this answer on a similar question:
https://stackoverflow.com/a/249084/1972372
This example worked, the alert only came up when the + was clicked on, but it is an inner function there, not a declared one like my "more(element)".
So my question is: Is it possible to set the onclick attribute to a declared function on a newly created element, like in my example, but prevent it from running immediately?
(The other article had a jQuery answer too, but unfortunately I have no knowledge about jQuery and cannot use it)
Yes, just wrap it in a "proxy" function:
plus.onclick = function() {
more(spantags.innerHTML);
};
Sure, but first you have to understand that plus.onclick = more(spantags.innerHTML); will call more with the argument spantags.innerHTML and assign the result that is returned from that function call to plus.onclick.
You could wrap it in a proxy function as suggested previously, or you could take advantage of the bind method to bind the arguments to the function itself:
plus.onclick = more.bind(null, spantags.innerHTML);
Read up on Bind here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

What is the difference between a function call and function reference?

I have the following function
function hello() {
alert("hi!");
}
Take this piece of code:
var elem = document.getElementById("btn");
elem.onclick = hello;
My question might be a bit hard to understand, so bear with me:
What EXACTLY differentiates THIS piece of code from a normal call, or what makes this piece of code require a reference to the function variable rather than a regular call? (hello();)
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Well, the onclick property expects a reference to a function, for it to execute when the element is clicked. Normally it's either:
element.onclick = funcRef;
or
element.onclick = function () {
funcRef();
};
(but of course, it's best to use addEventListener and attachEvent)
Notice how both of them are references to functions, not calling.
When something expects a reference, you don't call it...you assign a reference to it (first example).
When you want to specifically call a function, you call it with () (second example). But notice how in the second example, there's still a reference to a function that's assigned to onclick - it's just an anonymous function.
Probably the more important part:
Some people think you want to do this:
element.onclick = funcRef();
But that immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn't what you want.
I think the moral of the story is that when you want/need something to execute right now, you call the function. If the function is wanted for later use or needs stored, you don't call it.
Do you want it to execute NOW? Then call it.
a=hello() means "Call hello() ASAP, and set its return value to a".
On the other hand, a=hello means "a is an alias for hello. If you call a(), you get the same results as calling hello()"
You use the latter for callbacks, etc, where you want to tell the browser what you want to happen after an event occurs. For example, you may want to say "call hello() when the user clicks" (as in the example). Or, "When the AJAX query returns a result, call the callback() function on the returned data".
How can I know where I'm supposed to give a reference to the function, and when I'm supposed to actually call it?
Do you need the function to run now?
Than add the () to execute it
Do you need to function to be referenced so it is called later?
Do not add the ().
Pretty much all statements in JavaScript have a return value. Unless otherwise specified, functions in JavaScript will return undefined when called. So, the only context in which it would make sense to call your function in this assignment statement if it were to return a function:
function hello() {
return function() {
alert("hi!");
}
}
elem.onclick = hello();
A reference to your function is needed somewhere no matter how it gets called. The difference here is that you are not explicitly calling the hello function. You are assigning a reference to that function to the elem DOM node's onclick event handler so that when onclick is fired for that Node, your function gets called.
hello() means you call that function, which means the function will be executed directly.
while when you have elem.onclick = hello, this is called a callback. Where hello doesn't get executed directly but only when a certain event is fired (in this case when there's a click on the element)

Categories

Resources