This question already has answers here:
addEventListener calls the function without me even asking it to
(5 answers)
Closed 3 years ago.
How can I pass a variable to the onclick function? When using
var number = 123;
document.getElementById('myButton').onclick = myFunction(number);
It will run that function before even clicking the button because the function will be called and the return value will be put into the onclick, which doesnt help me
Without the "()" it will only call the function once I click the button, but how do I pass a variable then ?
var number = 123;
document.getElementById('myButton').onclick = myFunction;
function myFunction(i) {
i += 10;
alert(i);
}
One option would be to make the onclick an anonymous function to call myFunction.
var number = 123;
document.getElementById('myButton').onclick = () => {
myFunction(number)
}
function myFunction(i) {
i += 10;
alert(i);
}
<buton id="myButton"> Test button </buton>
Related
This question already has answers here:
How to pass arguments to addEventListener listener function?
(36 answers)
Closed last year.
I have some code where I'm passing a function as an event. I want to call the function when a button is clicked but the function requires a parameter. I can pass the parameter by writing btn.addEventListener('click', displayMessage('Test'); but the function is invoked immediately. I only want to call the function when the button is clicked. Is it possible to pass the parameter without immediately invoking the function?
function displayMessage(messageText) {
const html = document.querySelector('html');
const panel = document.createElement('div');
panel.setAttribute('class','msgBox');
html.appendChild(panel);
const msg = document.createElement('p');
msg.textContent = messageText;
panel.appendChild(msg);
const closeBtn = document.createElement('button');
closeBtn.textContent = 'x';
panel.appendChild(closeBtn);
closeBtn.addEventListener('click', () => panel.parentNode.removeChild(panel));
}
const btn = document.querySelector('button');
/* To avoid calling the function immediately, I do not use the function invocation
* operator. This prevents me from passing parameters, however.
*/
btn.addEventListener('click', displayMessage);
Run it as a callback.
btn.addEventListener('click', () => displayMessage('text'));
That way it will be executed only when the click event runs.
This question already has answers here:
Why do javascript variables in closure functions not reset to a default when called multiple times?
(2 answers)
Closed 2 years ago.
Simple JS logic question here.. In the below code, why does add() only set counter to 0 once? I feel like every time the function is called it should reset it to zero.
var add = (function () {
var counter = 0;
return function () {counter += 1; return counter}
})();
add(); // 1
add(); // 2
Thanks!
You're misunderstanding the code. The function add() does not contain the code var counter = 0.
Here's a rewrite of the exact same code that makes it more clear:
var add;
// Note: THIS function is NOT add()
(function () {
var counter = 0;
// THIS function is add()
add = function () {counter += 1; return counter}
})();
add(); // 1
add(); // 2
The code above does exactly the same thing as your original code except for how add was assigned. In your code it was assigned via a return value but in the above I simply assigned it directly as a global variable to make it more clear which function is add().
Another way to look at it that is more like your original code is to explicitly name the two functions:
var function1 = function () {
var counter = 0;
// The returned function is what will be assigned to add()
return function () {counter += 1; return counter}
}; // Do not call it yet since calling it was what was confusing you
var add = function1();
add(); // 1
add(); // 2
This question already has answers here:
javascript addEventListener not working more than once
(2 answers)
Closed 3 years ago.
I try to add an event listener on a button element. A named function with one argument is triggered on click.
My problem is that the function is automatically triggered on page loading and is not working on click. What is the problem?
Is it possible to use an anonymous function while passing an argument to it?
I tried with an named function simply declared and stored in a variable, both don't work.
I tried with an anonymous function but I didn't find out how to pass an argument to it.
var tab = [-2, 1, 4];
function additionne(x){
return x + 2;
}
function affiche(tab){
alert(additionne(tab[0]));
alert(additionne(tab[tab.length - 1]));
}
var bouton = document.getElementById('bouton');
bouton.addEventListener('click', affiche(tab));
I expect the event to be triggered on click and only then.
It is actually triggered only once, on page loading and not on click.
By writing as affiche(tab) you call the function immediately. In order to pass it as a callback with arguments, you can use bind() to bind scope and arguments.
var tab = [-2, 1, 4];
function additionne(x){
return x + 2;
}
function affiche(tab){
alert(additionne(tab[0]));
alert(additionne(tab[tab.length - 1]));
}
var bouton = document.getElementById('bouton');
bouton.addEventListener('click', affiche.bind(this, tab));
// ^^^^ ^^^
// scope argument(s)
<button id="bouton">Click me</button>
Hope this helps
You need to wrap it in a function.
var tab = [-2, 1, 4];
function additionne(x){
return x + 2;
}
function affiche(tab){
alert(additionne(tab[0]));
alert(additionne(tab[tab.length - 1]));
}
var bouton = document.getElementById('bouton');
bouton.addEventListener('click', function() { affiche(tab);});
<button id="bouton">Alert</button>
addEventListener takes a callback function as the 2nd argument.
You should use
function () { ... }
Instead of
affiche(tab)
Which is a function call (and not a function)
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 6 years ago.
I defined this class in JavaScript:
function Signal(lbl, ho, tag) {
this.lbl = lbl;
this.ho = ho;
this.tag = tag;
this.getstatus = function () {
if (this.ho) {
$.get('/get.cgi?' + this.tag + '=?0', function (data) {
console.log(data);
setTimeout(this.getstatus, 1000);
});
}
};
}
Once getstatus is called, it should start calling itself with setTimout, but it doesn't! It only works one time.
If I use a function without a class, it works!
Please help me out.
Thanks!
The problem is when getStatus is invoked by the timer, this inside the method does not refer to the object, you can pass a custom value for this using bind(). Also note that in the ajax callback this refers to the ajax settings object.
function Signal(lbl, ho, tag) {
this.lbl = lbl;
this.ho = ho;
this.tag = tag;
this.getstatus = function () {
if (this.ho) {
var signal = this;
$.get('/get.cgi?' + this.tag + '=?0', function (data) {
console.log(data);
setTimeout(signal.getstatus.bind(signal), 1000);
});
}
};
}
This question already has answers here:
standalone parentheses in javascript [duplicate]
(5 answers)
Closed 8 years ago.
I am studying JavaScript and I sometimes see something like this
function functionname()
{
// Some statements
} () ;
What does () following } mean?
Thanks a lot, experts on Stack Overflow
That is an IIFE (immediately invoked function expression). It is used to create a new scope. For example:
var x = 10;
(function() {
var x = 5;
}());
alert(x); // still 10
All it does is define and call the function at the same time.
IIFEs are also used to "save" the value of a variable. For example, this code won't work:
for (var i = 0; i < buttons.length; i ++) {
buttons[i].onclick = function() { alert(i) }
}
Every button will alert the last index when you click it, because after the loop is done i is buttons.length. To fix it, you would use an IIFE:
for (var i = 0; i < buttons.length; i ++) {
buttons[i].onclick = (function(i) {
return function() {
alert(i)
}
})(i)
}
More info on IIFEs
It calls the function.
var foo = function () { return 1; }();
alert(foo); // 1
There are lots of ways to define a function, when you do it like this ...
(function functionname(innerArguments){
// Some statements;
})(outerArguments);
... the function is executed as soon as this piece of code is interpreted;
its the same as:
function functionname(innerArguments){
// Some statements;
};
functionname(outerArguments);