30

If I wanted to auto-click a button element on page load, how would I go about this using jQuery?

The button html is

<button class="md-trigger" id="modal" data-modal="modal"></button>
starball
  • 20,030
  • 7
  • 43
  • 238
JStormThaKid
  • 1,794
  • 3
  • 20
  • 26

6 Answers6

47

You would simply use jQuery like so...

<script>
jQuery(function(){
   jQuery('#modal').click();
});
</script>

Use the click function to auto-click the #modal button

JStormThaKid
  • 1,794
  • 3
  • 20
  • 26
33

JavaScript Pure:

<script type="text/javascript">
document.getElementById("modal").click();
</script>

JQuery:

<script type="text/javascript">
$(document).ready(function(){
    $("#modal").trigger('click'); 
});
</script>

or

<script type="text/javascript">
$(document).ready(function(){
    $("#modal").click(); 
});
</script>
KingRider
  • 2,140
  • 25
  • 23
10

Use the following code

$("#modal").trigger('click');
Pete
  • 57,112
  • 28
  • 117
  • 166
user3164444
  • 155
  • 1
  • 7
6

I tried the following ways in first jQuery, then JavaScript:

jQuery:

 window.location.href = $(".contact").attr('href');
 $('.contactformone').trigger('click');  

This is the best way in JavaScript:

 document.getElementById("id").click();
Jud
  • 1,324
  • 3
  • 24
  • 47
Ravi Mane
  • 1,468
  • 2
  • 18
  • 24
2

You can use that and adjust the time you want to launch 1= onload 2000= 2 sec

$(document).ready(function(){
 $('#click').click(function(){
        alert('button clicked');
    });
  // set time out 2 sec
     setTimeout(function(){
        $('#click').trigger('click');
    }, 2000);
});
.container{
padding-top:50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="col text-center">
<button id="click" class="btn btn-danger">Jquery Auto Click</button>
  </div>
   </div>
Cudex
  • 49
  • 8
0

We should rather use Javascript.

    <button href="images/car.jpg" id="myButton">
        Here is the Button to be clicked
    </button>


    <script>

        $(document).ready(function(){
            document.getElementById("myButton").click();
        });

    </script>
mhtmalpani
  • 913
  • 1
  • 8
  • 11