If I have an existing click event associated with a button, can I use code to simulate that button being pressed so the code in the click event will run? I'm asking because I want there to be certain times where the user does not have to press the button for code to be executed. I would like to press the button automatically for them in certain instances if that makes any sense.
-
6Would you like me to Google this for you? – Amit Mar 11 '16 at 16:14
-
The same title of your question yields more results than answers given here. – Rajshekar Reddy Mar 11 '16 at 16:27
-
Possible duplicate of [How to simulate a click with JavaScript?](http://stackoverflow.com/questions/2705583/how-to-simulate-a-click-with-javascript) – Rajshekar Reddy Mar 11 '16 at 16:41
5 Answers
Three Choices:
You can call the click event handling function directly when appropriate:
if(timeIsRightForClick){ yourClickHandler(); }
You can simulate a button click by calling the
.click()
method of the button.$("#ButtonID").click()
Same as #2, but using jQuery's trigger() function, which can be used on standard events and custom ones:
$("#ButtonID").trigger("click");
http://api.jquery.com/trigger/
Choices #2 and #3 are usually better because they will cause the event handling function to receive a reference to the click event in case it needs to use that object. Choice #1 doesn't cause an actual click event (just runs the code you tell it to) and so no event object is created or passed to the event handler.

- 64,069
- 6
- 49
- 71
You can trigger a click event on an element by calling the .click() function on the element. By passing no value to the function the click event will fire, as opposed to setting up a listener for the click event.
If the button has an id of "form-btn", here's what that would like:
<button id="form-btn">Submit</button>
<script type="text/javascript">
//Setup the click event
$('#form-btn').on('click', function (e) {
alert('clicked!');
});
//Call the click event
$('#form-btn').click();
</script>
This should work fine, although I usually try to use a named function when setting up my event handlers, instead of anonymous functions. By doing so, rather than triggering the event I can call the function directly.
Note that in my experience, older browsers (IE6, IE7) sometimes limit what code-triggered events can do as a safety precaution for the user.
Here's documentation on the .click() function: http://www.w3schools.com/jquery/event_click.asp
Edit 1
I forgot that jQuery also has the .trigger() function, as used in choz's answer. That will also the job quite nicely as an alternative to .click(). What's nice about .trigger() is that it can trigger standard events as well as custom events, and also allow you to pass more data in your event.
var button = document.getElementById('yourButtonIdHere');
button.click();
This will fire a click event in the button

- 36
- 5