prismspecs
prismspecs

Reputation: 1489

How to automatically click() dynamically created elements

I understand that you can bind an event listener to dynamic elements, but I want to have the js automatically click them. As in, there is a webpage with a series of buttons that pop up, I want to automatically click thru them, but each successive button is loaded dynamically and so I cannot do it simply.

Here's what I was hoping would work (works if you type it into console one line at a time):

$(".begin").click().delay(200);

$(".answer[value='1']").click().delay(200);

$(".answer[value='10']").click().delay(200);

Upvotes: 0

Views: 556

Answers (1)

Yunhai
Yunhai

Reputation: 1411

If I don't misunderstand your problem. You want to click those buttons "once" they exist. Then you might create a timer after $('.begin')(here I assume the begin is to trig the button appear action) and constantly check those buttons and click them once it's active. It would look something like the following with setTimeInvertal(). And yes you need to create your own condition to stop or determine whether trig click or not.

You have to detect them manually, faster check = once (I assume you are not doing something illegally or abusing websites). The below code is a sample idea.

var btn_timer;

function startAction() {
  //for example check every 3s
  btn_timer = setTimeout(function(){
  //check if btn exists or not
  if($(".answer[value='1']").length) {
     $(".answer[value='1']").click().delay(200);
  }
  
  //condition to stop your timer, or you can manually call it somewhere else; 
  if(...some condition) StopAction();
  
  }, 3000); 
}

function StopAction() {
  clearTimeout(btn_timer);
}

Upvotes: 1

Related Questions