In JavaScript I can assign onclick by traditional way:
button.onclick = engineStop();
But how can I assign to onclick a function with parameter(s)?
This does not work >>
button.onclick = engineStop(this);
The function needs to receive this parameter to know which button has been clicked on.
Please advice... (no jQuery)
button.onclick = function() {engineStop(this);};
Using an anonymous function.
Like this:
function engineStop(param){
return function(){
//engineStop function's body here,
//which uses 'param' argument
};
}
button.onclick = engineStop(this);
Related
As it says in the title, I'm trying to create a button element in JavaScript, but when I try to set its onclick attribute, it just ignores it. I've looked at other questions with this topic on this site (such as this one), but everyone answers to put it in with HTML, like so:
<button id="buttonid" onclick="click(this);">
But my program dynamically creates the HTML buttons entirely with JavaScript (they're aligned on a table, so using a for loop is very useful. Plus I'm more familiar with JavaScript). Like this:
var b = document.createElement("button");
b.id = "buttonid";
b.onClick = "click(this);"; //I've tried many variations with no success
document.appendChild(b);
The button element is never declared in the HTML. I need a way to add the onclick attribute using JavaScript alone. I'm not very experienced with JQuery, so I would prefer just JavaScript.
Thank you in advance.
PS, I've tried all the following methods with both lowercase .onclick and camelcase .onClick:
b.onClick = "click(this);"; //just simply doesn't work
b.onClick = click(this); //actually runs the program there, with some ambiguous "this" object
b.onClick = click; //passes the actual function, but disallows the ability to pass the button's object (via "this")
You can use addEventListener to add the listener to the button and bind to pass the button as this for the handler function.
b.addEventListener(`click`, click.bind(b));
Or if you want to use onClick, just use bind:
b.onClick = click.bind(b);
Try this
var b = document.createElement("button");
b.onClick = function(){
alert("on click handler");
};
Try b.onClick = function(){ console.log("test"); }
I am not sure what your "click" function is. Maybe it isn't declared yet or something. Or what is happening is your function is named click "function click(){...}" which instead needs to be click = function(){...}
(function(){
// create the button
var buttonB = document.createElement('button');
buttonB.id = 'buttonB';
var textB = document.createTextNode('Button B');
buttonB.appendChild( textB );
// set the click event on the button
buttonB.addEventListener('click', function(){
// console.log('test');
// console.log( this );
clickFunc( this );
});
// populate the DOM-body with the button
document.body.appendChild( buttonB );
})();
function clickFunc( that ){
console.log( that );
}
My code to add a onclick function is as followsnewbutton.onclick = whoWon(this.id)
Other Relevant Code
var winner;
function whoWon(name){
winner = name
}
My problem is that the onclick when i try to assign it executes and doesn't add the onclick. I know this because when I create the new button the variable winner is always the most recent button created. Also when I inspect the element in google chrome the only thing that is assigned is the ID and the Class.
newbutton.onclick = whoWon(this.id) will actually call the whoWon function.
You need to pass the whoWon as is, without calling it and bind it the this.id. This should do the trick:
newbutton.onclick = whoWon.bind(null, this.id)
Or as mentioned by #styfle in the comments, you could create an anonymous function:
newbutton.onclick = () => whoWon(this.id)
Your code newbutton.onclick = whoWon(this.id) executes whoWom(this.id) and assigns the result of it (which is undefined in this case) to newbutton.onclick.
What you really should be using is:
newbutton.addEventListener('click', whoWon);
From there you can access the equivalent of this.id with event.target.id
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');
}
Using google apps script I'm having trouble running a js function which passes parameters. When I add the parameters it will always run the code when the page loads instead of when the button is clicked.
Direct from the HtmlService example, it is OK - it runs when the button is pressed...
document.getElementById('button1').onclick = doSomething;
But when I add a parameter to the call (and function) as below, it runs just once when the page loads (and not when the button is pressed)...
document.getElementById('button1').onclick = doSomething('with_this_parameter');
Any insight into this behaviour would be greatly appreciated... sorry if the answer is obvious!
When you say
document.getElementById('button1').onclick = doSomething('with_this_parameter');
This means call doSomething('with_this_parameter') and then assign the returned value to document.getElementById('button1').onclick. Hence that is why it gets called when code reaches that line. Whether the value is assignable to that property or not is another question, but that is why it gets called.
Use it like this
document.getElementById('button1').onclick = function(){
doSomething('with_this_parameter');
}
Reference: This solution was given by Mark Linus.
Do like this:
document.getElementById('button1').onclick = function(){
doSomething('with_this_parameter');
}
To assign a reference of function to some variable, you do:
var a = doSomething;
where doSomething is a function.
But when you have to pass parameters and assign that function
var a = doSomething(b);
this will cause trouble as while assigning the function to the variable, it gets called and not when it is intended to be called.
To overcome this, you can use arrow functions or simple function to call your own function with params.
var c = () => doSomething(d);
This actually is understood as var c = anonymous_function;
or
var c = function() {
doSomething(d);
}
Hence you can do:
document.getElementById('button1').onclick = () => doSomething('with_this_parameter');
I usually do clickHandlers like so:
// create button here or get button...
var button1 = document.getElementById('button1').setName('button1');
var clickHandler = app.createServerClickHandler('doSomething');
button.addClickHandler(clickHandler);
function doSomething(e){
var button1 = e.parameter.button1;
<do something with var button>
}
I'm not sure what parameter you are adding, but you need to add a callback element to pass it if it isn't passed by the button itself via a .setId/getId or .setTag/getTag. If it is from a textbox:
var textbox = app.createTextBox();
var button1 =
app.createButton.setName('button1');
var clickHandler =
app.createServerClickHandler('doSomething').addCallbackElement(textBox);
button1.addClickHandler(clickHandler);
Hope this helps!
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.