js trigger click code example

Example 1: jquery trigger

$( "#foo" ).on( "click", function() {
  alert( $( this ).text() );
});
$( "#foo" ).trigger( "click" );

$( "#foo" ).on( "custom", function( event, param1, param2 ) {
  alert( param1 + "\n" + param2 );
});
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );

Example 2: js trigger click

var element = document.getElementById('element');
element.click();

Example 3: js trigger click

// On mouse-over, execute myFunction
function myFunction() {
  document.getElementById("myCheck").click();
}

Example 4: js trigger click

<a href="#" target="_blank" onclick="javascript:Test("Test");">MSDN</a>

Example 5: js trigger click

const body = document.body;

body.addEventListener('click', e => {
  console.log('clicked body');
});

console.log('Using click()');
body.click();

console.log('Using dispatchEvent');
body.dispatchEvent(new Event('click'));

Example 6: js trigger click

<form>
  <input type="checkbox" id="myCheck" onmouseover="myFunction()" onclick="alert('click event occurred')">
</form>