How to perform button click operation using javascript - javascript

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);

Related

Why can't I log this array of td elements? [duplicate]

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!

Javascript function not called on dynamically created button in C#

I have created button in C# dynamically and added client side event
but that function not getting called instead getting error as:
Uncaught ReferenceError: setPropertyLocation is not defined
Javascript:
function setPropertyLocation() {
alert('Hello');
}
C#:
btnMap.Attributes.Add("type", "button");
btnMap.Attributes.Add("title", "Map");
btnMap.UseSubmitBehavior = false;
btnMap.OnClientClick = "setPropertyLocation();return false";
btnMap.ID = "btnMap" + objPMPropTypestructure.PMFields[fieldcnt].SystemName;
btnMap.CssClass = "dataButton";
btnMap.Text = "G";
btnMap.Enabled = true;
tablecell.Controls.Add(btnMap);
//Try to use this.
document.addEventListener('DOMContentLoaded', function () {
document.getElementById ("btnMap").addEventListener ("click", setPropertyLocation, false);
});
Consider creating this button via JavaScript instead of C#. I assume you are using an update panel. Update panels are a mess. They don't update the DOM elements, they just get rid of the old wrapper and create an entire new, what sets to undefined all JavaScript references to any element in that wrapper.
Well, some times we don't have time to refactor the solution, so we must work with what we have.
You may try add an onclick attribute to the element, just like you did for type and title attribtues.

Function is being called when page loads instead of on click event

I am trying to get this function to be called via click event, but for some reason it is being called when page loads. I am completely baffled on why my function is reacting this way.
Here is my function
var registerTab = function(panel){
var active = 'off';
if($('#'+panel).css('left') <= '0'){
$('#'+panel).animate({left: '0'});
active = 'on';
} else {
$('#'+panel).animate({left: '-380px'});
}
};
$(function() {
tabRegister.on('click', registerTab('sidePanel'));
});
The weird thing is if i call it when i remove the passed variable and hard-code the selector in it works fine which again makes no since to me. Please any help would be very helpful and save me some hair.
registerTab('sidePanel')
This call will cause the function to be called immediately. I think what you really want is this:
tabRegister.on('click', function () {
registerTab('sidePanel')
});

jQuery bind custom function to appended element

I am trying to create a web app that will allow a user to define a custom JavaScript function and then add a button to their user interface that well preform that function.
Here is a sample of the code
var customCommands = {
command1: {
text: 'Hello Console',
cFunctionRun: function() {
console.log('hello Console!');
}
},
command2: {
text: 'Hello World',
cFunctionRun: function() {
alert('hello World!');
}
}
}
Then I wrote a small function that loops though and builds the buttons and adds them to the user interface. The problem is when I append the elements to the user interface than click on the buttons nothing works...
Here is one of the methods I tried
for (var cmd in customCommands) {
command = customCommands[cmd];
button = $('<button/>').html(command.text).on('click',
function(){
console.log(command.text);
command.cFunctionRun();
}
);
}
buttonContainer.append(button);
Now my loop builds everything just fine and even the .on('click') works, but it always displays the text of the lasted added command?
here is http://jsfiddle.net/nbnEg/ to show what happens.
When you actually click, the command variable points to last command (as the whole loop has already run). You should maintain data state per button which tells it which command to invoke. You should do this.
for(var i in customCommands) {
if(customCommands.hasOwnProperty(i)){ //this is a pretty important check
var command = customCommands[i];
button = $('<button/>').html(command.text).data("command_name", command).on('click', function(){
console.log($(this).data("command_name").text);
$(this).data("command_name").cFunctionRun();
});
$("body").append(button);
}
}
JSFiddle
all you need is passing the parameter with function, you should try this
It's a (missing) closure problem. The event handler will keep a reference to the value of command on the last iteration of the loop. To solve it you can create a new scope, using an immediately invoked function:
for(var cmd in customCommands) {
(function(command){
button = $('<button/>').html(command.text).on('click',
function(){
console.log(command.text);
command.cFunctionRun();
}
);
buttonContainer.append(button);
}(customCommands[cmd]));
}
Since the buttons should be unique (no reason for creating duplicates), I'm setting the button id to the name of the customCommands (command1 and command2 in this example). This example could easily be adapted to use any of the relative attributes (data-*, name, etc...).
Create a click event listener on document for whenever one of your buttons are pressed. Then call the function associated with the given id.
$(document).on("click", "button", function(){
customCommands[this.id].cFunctionRun();
});
for(var command in customCommands){
var button = $('<button id="' + command +'"/>').html(customCommands[command].text);
$("body").append(button);
}
EXAMPLE

Jquery if its the first time element is being clicked

I need my script to do something on the first time an element is clicked and continue to do something different on click 2,3,4 and so on
$('selector').click(function() {
//I would realy like this variable to be updated
var click = 0;
if (click === 0) {
do this
var click = 1;
} else {
do this
}
});//end click
really I think it should rely on the variables but I can't think of how to update the variable from here on out any help would be awesome.
Have a look at jQuery's .data() method. Consider your example:
$('selector').click(function() {
var $this = $(this),
clickNum = $this.data('clickNum');
if (!clickNum) clickNum = 1;
alert(clickNum);
$this.data('clickNum', ++clickNum);
});
See a working example here: http://jsfiddle.net/uaaft/
Use data to persist your state with the element.
In your click handler,
use
$(this).data('number_of_clicks')
to retrieve the value and
$(this).data('number_of_clicks',some_value)
to set it.
Note: $(this).data('number_of_clicks') will return false if it hasn't been set yet
Edit: fixed link
Another alternative might be to have two functions, and bind one using the one function in $(document).ready() (or wherever you are binding your handlers), and in that function, bind the second function to be run for all subsequent clicks using bind or click.
e.g.
function FirstTime(element) {
// do stuff the first time round here
$(element.target).click(AllOtherTimes);
}
function AllOtherTimes(element) {
// do stuff all subsequent times here
}
$(function() {
$('selector').one('click', FirstTime);
});
This is super easy in vanilla Js. This is using proper, different click handlers
const onNextTimes = function(e) {
// Do this after all but first click
};
node.addEventListener("click", function onFirstTime(e) {
node.addEventListener("click", onNextTimes);
}, {once : true});
Documentation, CanIUse
If you just need sequences of fixed behaviors, you can do this:
$('selector').toggle(function(){...}, function(){...}, function(){...},...);
Event handlers in the toggle method will be called orderly.
$('#foo').one('click', function() {
alert('This will be displayed only once.');
});
this would bind click event to Corresponding Html element once and unbind it automatically after first event rendering.
Or alternatively u could the following:
$("#foo").bind('click',function(){
// Some activity
$("#foo").unbind("click");
// bind it to some other event handler.
});

Categories