jtrdev
jtrdev

Reputation: 932

Document ready button.click only works in console

I have a button<button id="stbutton"></button> and I can enter into the Chrome Dev Console $('#stbutton').click(); and it works. Sounds easy enough, however:

$(document).ready(function () {
    $("#stbutton").click();
});

Doesn't work. Also tried waiting for the parent div to load, no dice,

 $('#panel').ready(function () {
    $("#stbutton").click();
});

As for this page, I know it works in console. And jquery is definitely being loaded before it hits this line of code.

Upvotes: 6

Views: 20144

Answers (2)

jtrdev
jtrdev

Reputation: 932

$(window).load(function () {
    $('#stbutton').click();
})

I found the magic that is window.load!

Upvotes: 4

Marcos Casagrande
Marcos Casagrande

Reputation: 40434

As @charlietfl pointed out, you're probably triggering the event before attaching the click listener to the element.

$(document).ready(function(){

   $("#stbutton").click(); //This doesn't work
  
  
   $("#stbutton").on("click", function(){
      alert("clicked");
   }); 
  
   $("#stbutton").click(); //trigger event after listening to it.

});
#stbutton {
  background: #000;
  width: 100px;
  height: 100px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  
<div id="stbutton"></div>

Upvotes: 8

Related Questions