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.
.click()
does not work with Android (look at mozilla docs, at mobile section). You can trigger the click event with this method:From this post
I'm quite ashamed that there are so many incorrect or undisclosed partial applicability.
The easiest way to do this is through Chrome or Opera (my examples will use Chrome) using the Console. Enter the following code into the console (generally in 1 line):
This will generate the required result
IE9+
Usage example:
Source: https://plainjs.com/javascript/events/trigger-an-event-11/
What
does is exactly calling the
onclick
function ofl
, that is, if you have set one withl.onclick = myFunction;
. If you haven't setl.onclick
, it does nothing. In contrast,simulates a click and fires all event handlers, whether added with
l.addEventHandler('click', myFunction);
, in HTML, or in any other way.Use a testing framework
This might be helpful - http://seleniumhq.org/ - Selenium is a web application automated testing system.
You can create tests using the Firefox plugin Selenium IDE
Manual firing of events
To manually fire events the correct way you will need to use different methods for different browsers - either
el.dispatchEvent
orel.fireEvent
whereel
will be your Anchor element. I believe both of these will require constructing an Event object to pass in.The alternative, not entirely correct, quick-and-dirty way would be this:
Here is what I use: http://jsfiddle.net/mendesjuan/rHMCy/4/
Updated to work with IE9+
Note that calling
fireEvent(inputField, 'change');
does not mean it will actually change the input field. The typical use case for firing a change event is when you set a field programmatically and you want event handlers to be called since callinginput.value="Something"
won't trigger a change event.