I created a function that makes buttons because I have to make several:
makeButton(function, "text")
The parameters are the function it will be calling "onclick" and the text that will show on the button.
Now I have two of them calling the same function but I want the function to behave in one way if one calls and other way if the other is calling.
I tried to call the function like this:
makeButton(function(flag = true), "text")
And then in the function:
if(flag == true) doSomething;
else doSomethingElse;
Maybe this won't work, but the thing is when I create the button like this:
makeButton(function(flag = true), "text")
It executes the function when creating the button, and I wanted it to execute only onclick.
Other thing I thought was in the function:
if(buttonA) do something;
if(buttonB) do somethingElse;
But I need the function to know which button has called for it...
Do you have any suggestion to do this in other way? Only simple JavaScript please!
The function looks like this:
function makeButton(function, text){
var button = document.createElement('BUTTON');
var btTxt = document.createTextNode(text);
button.style.color = '#006633';
button.style.fontWeight = 'bold';
button.onclick = function;
button.appendChild(btTxt);
button.style.margin = '5px';
document.body.appendChild(button);
}
As you stated, the code:
makeButton(myFunction(flag = true), "text")
Is unfit for purpose because it executes the function rather than passing it as an argument. Instead, use the bind() function:
makeButton(myFunction.bind(null, true), "text")
This will pass your onclick function as an argument, with its first argument set to true. This can act as your flag:
function myFunction (flag) {
if (flag) //do something
else //do something else
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With