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
Related
I'd like to remove an event listener from an element but its function has to take a parameter and it seems to not work. I was trying to find a solution on internet but anyone seems to have the same problem as me.
The role of the function is to simply change the visibility of the element
It doesn't make much sense to remove the listener immediatly but it's only for the example.
function createHoverEqElts() {
slotElts.forEach(function(slot, i) {
if(existValueElts[i].value == "true") {
let infoElt = document.createElement('div');
infoElt.style.position = "relative";
infoElt.style.bottom = "71px";
slot.appendChild(infoElt);
slotListenersElts.push(infoElt);
slot.addEventListener('mouseover', _slotListener(infoElt));
slot.removeEventListener('mouseover', _slotListener(infoElt));
slot.addEventListener('mouseout', function() {
infoElt.style.visibility = "hidden";
});
}
});
}
let _slotListener = function(elt) {
return function() {
elt.style.visibility = "visible";
}
}
I think your problem is that you return a function for some reason. You should pass a function that does something. Try this.
let _slotListener = function(elt) {
elt.style.visibility = "visible";
}
And then do this. In this scenario, you can also pass null instead of this, try either one.
slot.addEventListener('mouseover', _slotListener.bind(this, infoElt));
Since your function returns an anonymous function, you lose its reference. removeEventListener needs the same occurrence to work properly.
In other words _slotListener(infoElt) == _slotListener(infoElt) will always return false, so removeEventListener('event', _slotListener(infoElt)) will never work.
Store the function returned by _slotListener() somewhere and use it back to remove the event. In your example, it could be in a variable. In a more complex example, it could be in an object with some kind of reference or in a property in the DOM element.
var callback = _slotListener(infoElt); // save reference
slot.addEventListener('mouseover', callback);
slot.removeEventListener('mouseover', callback);
The reason you cannot remove the event listener effectively is because the function that you are passing to addEventListener is not the same as the function that you are passing to removeEventListener. JavaScript cannot compare two functions that have the exact same contents and tell they are the same function. Every single time you call _slotlistener, it creates a new function that is not the same as functions that were previously returned by _slotlistener. Instead, the proper way to do this would be to assign the result of _slotlistener to a variable, and then pass that variable into addEventListener and removeEventListener. For example,
var myListenerFunc = _slotListener(elt);
slot.addEventListener("mouseover", myListenerFunc);
slot.removeEventListener("mouseover", myListenerFunc);
I have this simple onclick eventfunction and i would like to know if it's possible to acces the variable that is inside it and use it outside this function, if not is there a way to do something similar?
document.querySelector('.check-parent').addEventListener('click', function() {
var a = 'abc';
return a;
});
console.log(a);
P.S.
In my homepage code i have 3 forms, each form has one id and it needs to display errors in case the fields are not completed properly. And when i click submit i get the parent id and that id goes in a switch function and determins with form it was and what errors needs to display
You'll have to get a few things correct:
The this variable changes inside the callback since the scope changes.
Hence bind outer this to your clickhandler(bind(this) in below snippet)
console.log(a) would not print undefined since it's again in different scope.
You'll have to trigger this call only after a click event is performed. Hence wrap it in a function & call this from the handler by passing the value.(this.fromClick(innerVariable) in below snippet)
Below's a sample snippet(ES5 demo & ES6 demo):
this.count =0;
document.getElementById('myButton').addEventListener('click', function() {
//Access outer variables
this.count++;
document.getElementById('buttonCount').innerHTML = this.count;
//Send something outside
var innerVariable = 'String from click handler!!';
this.fromClick(innerVariable);
}.bind(this));
this.fromClick = function (innerVariable) {
alert(innerVariable);
}
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!
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);