87

I need to use JavaScript to simulate the action of clicking buttons. How do I achieve it? Can I achieve it with jQuery?

6 Answers 6

151

Yes, you can do it with jquery. Use trigger function. Here documentation. Here is sample:

$('#foo').trigger('click');
Sign up to request clarification or add additional context in comments.

3 Comments

Is this solution in any way to be preferred over the vanilla .click() method? Is there perhaps some runtime cost difference between the two?
I can't seem to get this to work in IE. Anyone else? $(this).trigger('click');
Disregard, can't seem to add click after adding event.preventDefault();
29

You can execute the click event handler assigned to a button control:

$("#mybutton").click();

Comments

15

Simply .click():

$("#theButton").click();

Comments

3

Following code will print clicked two times one from $('.submitBtn').click(); and other $('.submitBtn').trigger('click')

$(document).ready(function() {

  $('.submitBtn').on('click', function() {

   console.log("Clicked!");

  })

$('.submitBtn').click();
$('.submitBtn').trigger('click')



});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<button menu="submitBtn" class="submitBtn len4 btn" title="submit" data-code-m="sbm.submit"> Click me
        </button>

Comments

3

Please try following code e.g.:

setTimeout(function() {
    $(".class_name").trigger('click');  
}, 2000);

Comments

0

Wrapping it in this 'anonymous document ready function' will make sure the button is there before you click it. Just in case it tries to click before the element you want to click is loaded. This would fix that issue.

Also, remember that an ID uses a hash (i.e. #close-button) but if you want to click an element that has a CLASS then swap the hash for a single dot (i.e. .close-button).

jQuery(document).ready(function() {
        $("#close-button").trigger('click');    
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.