How can I simulate a click event using JavaScript?

I’m trying to simulate a click event on an element using JavaScript. I’ve written the following code:

function simulateClick(control) {
  if (document.all) {
    control.click();
  } else {
    var evObj = document.createEvent('MouseEvents');
    evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
    control.dispatchEvent(evObj);
  }
}
<a href="http://www.google.com" id="mytest1">test 1</a><br>

<script type="text/javascript">
    simulateClick(document.getElementById('mytest1'));
</script>

However, this is not working as expected. Can someone help me identify what’s wrong with my approach?

Your approach is almost there, but there’s a simpler and more modern way to simulate a click event using click() directly, which should work across all modern browsers.

Here’s a refined version of your function:

function simulateClick(control) {
  control.click();
}

This will simulate a click event in modern browsers, and you don’t need to worry about creating and dispatching mouse events manually.

You can now call this function as you did before:

simulateClick(document.getElementById('mytest1')); This works well across the majority of modern browsers, including Chrome, Firefox, and Safari.

To simulate a click event in modern JavaScript, you can simplify your code to use click() directly without needing to create a custom MouseEvent. Here’s how you can do it:

function simulateClick(control) {
  control.click();  // Directly simulates a click event
}

With this, your HTML should work as expected:


<a href="http://www.google.com" id="mytest1">test 1</a><br>

<script type="text/javascript">
    simulateClick(document.getElementById('mytest1'));
</script>

This will trigger the click event on the element, navigating to Google. The use of click() directly is the most straightforward and effective way.

The issue you’re facing is likely related to how the event is being dispatched, especially in older browsers or different environments.

Modern browsers support simulating a click event directly using click() without needing to create and dispatch MouseEvent. Here’s a cleaner approach:

function simulateClick(control) {
  if (control) {
    control.click(); // Simulates the click directly
  }
}

Then simply call the function on the element:

<a href="http://www.google.com" id="mytest1">test 1</a><br>

<script type="text/javascript">
    simulateClick(document.getElementById('mytest1'));
</script>

This method works across all modern browsers and is much cleaner than manually dispatching events.