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!
Related
I am trying to perform click operation for Buy now button in flipkart through javascript by executing it in chrome console. Using below code
function timeout_trigger() {
var buynowButton = document.getElementsByClassName("_2AkmmA _2Npkh4 _2kuvG8 _7UHT_c")[0];
console.log(buynowButton)
buynowButton.click();
}
setTimeout('timeout_trigger()', 2000);
I am able to see the button element in console log as i printed using
console.log(buynowButton)
But, When click method on buynowButton is not working for that flipkart page
buynowButton.click();
Flipkart don't use click() event for theirs buttons!
It uses Ruby's onClick and some sort of complicated system to prevent auto clicking on their site.
They use function called handleClick, that they give to button as if it was named onClick but really is called o(). And they use special kind of Event to handle it. That's why you cannot use .click(), they blocked it by setting btn.click = ()=>{}. They also used very complicated system to prevent clicking automatically, so basicly you just have to figure out how to bypass that somehow.
dont call the timeout_trigger as a string and pass it as a reference instead.
try :
function timeout_trigger() {
var buynowButton = document.getElementsByClassName("_2AkmmA _2Npkh4 _2kuvG8 _7UHT_c")[0];
console.log(buynowButton)
buynowButton.click();
}
setTimeout(timeout_trigger, 2000);
EDITED
You can use it like this
document.getElementById("btn").addEventListener("click", function(){
console.log('Clicked');
})
var clickBtn = function() {
var buynowButton = document.getElementById('btn');
buynowButton.click();
}
setTimeout(function(){
clickBtn();
}, 1000)
<button id="btn">Click</button>
Removed jQuery and added back.
You can just put the function reference in the setTimeout's first parameter.
var timeout_trigger = function(){
var buynowButton = document.getElementsByClassName("_2AkmmA _2Npkh4 _2kuvG8 _7UHT_c")[0];
console.log(buynowButton)
buynowButton.click();
}
setTimeout(timeout_trigger, 2000);
Triggering a button in jQuery is easy.
$("#id").trigger('click');
or simply
$("#id").click();
Also, don't call your timeout function as a string.
setTimeout(timeout_trigger(), 2000);
I'm new to JS, I watched some crash course on YouTube and try to do it on the same time. I'm using Visual Studio Code with an extension live server in order to see changes quickly.
In my JS code:
//SUBSCRIBE
var subscribeEmail = document.getElementById('subscribe-email');
var subscribeSubmit = document.getElementById('subsribe-link-btn');
//HEADER
var headerRootWrapper = document.getElementById("navbar-wrapper");
console.log(headerRootWrapper);
var show = document.getElementById('sidebar-wrapper');
//LOGO
var webLogo = document.getElementById('logo');
console.log(webLogo);
//MENU BAR
var menuBar = document.getElementById('menu-bar').addEventListener('click', menuSlideLeft());
console.log(menuBar);
var sideMenuId = document.getElementById('sidebar-wrapper');
//SEARCH BAR
var searchBar = document.getElementById('searchBarShow').addEventListener('click',searchStart());
// METHOD
function menuSlideLeft() {
alert("Fire");
}
From my Html file, I added the js script at the bottom (not inside the body tag) . It always execute the method menuSlideLeft() at the start without making me click the menuBar.
<script src="js/jscript.js"></script>
Remove the parentheses from your event listener, that calls the function. Instead use:
.addEventListener('click', menuSlideLeft);
You are calling function in this line
var menuBar = document.getElementById('menu-bar').addEventListener('click', menuSlideLeft());
check the part menuSlideLeft() in addEventListener function.
What you should do is
var menuBar = document.getElementById('menu-bar').addEventListener('click', menuSlideLeft);
i-e just pass the reference of the function. Don't call it. it will be called in that event
You are calling function instead of passing it as parameter.
Solution:
document.getElementById('menu-bar').addEventListener('click', menuSlideLeft);
There is probably a really easy solution to this but I cannot for the life of me work out how to fix this issue, and nothing I have found so far has done the trick.
I'm trying to get the function "validate" to run when the form "apply" is submitted:
function init() {
var applyForm = document.getElementById("apply");
setJobValue();
applyForm.onsubmit = validate;
}
Validate looks like the following:
function validate() {
alert("If this alert is up then validate is running");
var dateOfBirth = document.getElementById("dob").value;
var state = document.getElementById("state").value;
var postcode = document.getElementById("postcode").value;
etc.
The function "setJobValue" is running (so I know init is working) and there are no errors in the console, but what adjustments would I have to make for validate to be called?
Well, what happens is that when you put your code above in the head, the script runs when the HTML gets rendered. So during that time, it allocates different memory and function blocks. So when you call that function again, then it gives you different results and no errors because of the existing references. Well its a bit weird but its the way JS works and it is always recommended to put your JS code at the bottom of the page.
You can directly call validate method from your init method instead.
function init() {
var applyForm = document.getElementById("apply");
setJobValue();
validate();
}
When we assign a function to an event, it will fire at last.
so in your case, This should work
function init() {
var applyForm = document.getElementById("apply");
setJobValue();
applyForm.onsubmit = functionToSave;
}
And call your validation method on the submit button onclick event.
In the code below, initializeBoard has access to the property, and the console returns 'white' when I start the script. But when I click inside the window, I get 'undefined'. What obvious thing am I missing? (Bonus: what's the search query that'd have led me to the answer without having to ask?)
var view = {
currentMove: 'white',
initializeBoard: function() {
console.log(this.currentMove);
},
click: function(e) {
console.log(this.currentMove);
}
}
window.onload = function() {
view.initializeBoard();
document.onclick = view.click;
}
The value of this is determined by how the function is called, not by where it is first assigned.
You are copying the (reference to the) function to document.onclick.
When the click event happens document.onclick is called. view.click is not called (even though it has the same value as document.onclick). This means that this is document not view.
Use bind if you want to create a wrapper function that calls the original function in the right context.
document.onclick = view.click.bind(view);
When I assign the event handler without parameters, it works: http://jsfiddle.net/mUj43/
function show(){
alert('work');
}
var myButton = document.createElement("input");
myButton.type="button";
myButton.value="click";
myButton.onclick=show;
var where = document.getElementById("where");
where.appendChild(myButton);
but if I pass parameters, it doesn't work: http://jsfiddle.net/mUj43/1/
myButton.onclick = show('test');
How can I use function with parameters in dynamically created elements?
You can't do that, you could use partial application by creating a new function and then attach that as event handler:
myButton.onclick=show.bind( myButton, 'test');
http://jsfiddle.net/mUj43/2/
Docs (which I recommend you read because this function is useful for many other things as well) and compatibility information: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
You'll have to create your own closure:
myButton.onclick = function () {
show.call(this, 'test');
};
You could also use #Esailija's bind method, but this one has deeper browser support.
try:
myButton.onclick = function(){show("test");}
or :
myButton.onclick = function(){ show.call( this, "test");}
if you want to retain the element object context inside the show function
That's because when you add events you need a function reference.
In your first example, show is a reference to a function.
In your second example, show('test') is a call to the function show, which returns nothing, and nothing isn't a function reference.
That's why when you load the page, it alerts "work" (the function is called), but when you click the button no function is called.
Then, you need a function.
You can declare it:
myButton.onclick=f;
function f(){
show('test')
}
Or you can use an anonymous one:
myButton.onclick=function(){
show('test')
}