Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 264
jtrdev Avatar asked Mar 17 '16 00:03

jtrdev


1 Answers

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>
like image 165
Marcos Casagrande Avatar answered Oct 13 '22 01:10

Marcos Casagrande