How to trigger click using jQuery or Javascript

Sometime we need to manually trigger a click event on an element (e.g. button). Here are Javascript and jQuery code snippets for this. This is the snapshot of outcome where we trigger a click from javascript.

javascript-trigger-click

Trigger click in jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<button id="id1" onclick="handle_click()">click me</button><br/><br/>
<div id="msg"></div>
<script type="text/javascript">
function handle_click() {
  document.querySelector("#msg").innerHTML = "clicked";
}
jQuery("#id1").trigger("click");
</script>
refresh

Trigger click in Javascript

<button id="id1" onclick="handle_click()">click me</button><br/><br/>
<div id="msg"></div>
<script type="text/javascript">
function handle_click() {
  document.querySelector("#msg").innerHTML = "clicked";
}
document.querySelector("#id1").click();
</script>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments