How can I trigger a JavaScript event click

user171523 picture user171523 · Mar 4, 2010 · Viewed 581.2k times · Source

I have a hyperlink in my page. I am trying to automate a number of clicks on the hyperlink for testing purposes. Is there any way you can simulate 50 clicks on the hyperlink using JavaScript?

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

I'm looking for onClick event trigger from the JavaScript.

Answer

instanceof me picture instanceof me · Mar 4, 2010

Performing a single click on an HTML element: Simply do element.click(). Most major browsers support this.


To repeat the click more than once: Add an ID to the element to uniquely select it:

<a href="#" target="_blank" id="my-link" onclick="javascript:Test('Test');">Google Chrome</a>

and call the .click() method in your JavaScript code via a for loop:

var link = document.getElementById('my-link');
for(var i = 0; i < 50; i++)
   link.click();