1

I am javascript/jquery noobie. Trying to hack together something for personal project How to access elements using jquery from within setTimeout. I am trying to click a button after three seconds and I tried the following Eg

setTimeout((){$("#id1").click()}, 3000) However I am not able to access any element from within the setTimeout. I have to hold reference to the element outside and then click.

var ele = $("#id1");
setTimeout((){ele.click()}, 3000)

How can I acces elements from within a setTimeout or setInterval

EDIT: I do not have access to all the div elemets and cannot store in a variable or attach it to a timeout I have to click a button after 3 seconds. Another button will be available after I click this. The second button is not hidden but simple not available. So I need something like this

$("#id1").click();
    setTimeout((){
    $("#id2").click();
    }, 3000);
}, 3000)
user009122
  • 125
  • 2
  • 9

4 Answers4

0

you could use .bind(null,somethinWithDom) in the callbackFunction and now the function has a new parameter (somethingWithDomBinded) => {}

But for practical uses you need to use Event listeners, instead passing you domThing you could trigger an event in the callback then listen and trigger whatever you want

sdykae
  • 108
  • 1
  • 7
0

First you have syntax error in you code

ur Html

<button id="id1">Click</button>

ur jQuery

setTimeout(() => {
    var ele = $("#id1");
    ele.click(() => {
      console.log(ele.html())
    })
  }, 3000);

Inside click You have to call another func and you can put your logic there

sayalok
  • 882
  • 3
  • 15
  • 30
0

You are simply missing the Arrow operator =>. Check this out:

$(document).ready(function(){
  setTimeout(() =>{
   console.log($("#id1"));
 }, 3000);
});
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<button id="id1">Click me</button> 

Or you can just access it like this:

setTimeout(() => console.log($("#id1")), 3000);
HenryDev
  • 4,685
  • 5
  • 27
  • 64
0

I used this mentioned in the stackoverflow answer to satisfy my use case

user009122
  • 125
  • 2
  • 9