How can I trigger a JavaScript event click

Multi tool use
Multi tool use


How can I trigger a JavaScript event click



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.




8 Answers
8



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


element.click()



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:


.click()


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





NB this is for quick testing purpose. For a more robust, standard-compliant, cross-browser solution, see Juan's answer.
– instanceof me
Sep 2 '14 at 11:52





I don't understand the loop and this didn't work on mobile.
– im_benton
Jan 11 '16 at 22:33





@im_benton: The loop was for OP's specific needs. If you just need to trigger a click event, you can omit the line that begins with for(.
– rinogo
Jul 7 '17 at 17:35


for(



Here is what I use: http://jsfiddle.net/mendesjuan/rHMCy/4/



Updated to work with IE9+


/**
* Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
* by testing for a 'synthetic=true' property on the event object
* @param {HTMLNode} node The node to fire the event handler on.
* @param {String} eventName The name of the event without the "on" (e.g., "focus")
*/
function fireEvent(node, eventName) {
// Make sure we use the ownerDocument from the provided node to avoid cross-window problems
var doc;
if (node.ownerDocument) {
doc = node.ownerDocument;
} else if (node.nodeType == 9){
// the node may be the document itself, nodeType 9 = DOCUMENT_NODE
doc = node;
} else {
throw new Error("Invalid node passed to fireEvent: " + node.id);
}

if (node.dispatchEvent) {
// Gecko-style approach (now the standard) takes more work
var eventClass = "";

// Different events have different event classes.
// If this switch statement can't map an eventName to an eventClass,
// the event firing is going to fail.
switch (eventName) {
case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
case "mousedown":
case "mouseup":
eventClass = "MouseEvents";
break;

case "focus":
case "change":
case "blur":
case "select":
eventClass = "HTMLEvents";
break;

default:
throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
break;
}
var event = doc.createEvent(eventClass);
event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.

event.synthetic = true; // allow detection of synthetic events
// The second parameter says go ahead with the default action
node.dispatchEvent(event, true);
} else if (node.fireEvent) {
// IE-old school style, you can drop this if you don't need to support IE8 and lower
var event = doc.createEventObject();
event.synthetic = true; // allow detection of synthetic events
node.fireEvent("on" + eventName, event);
}
};



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 calling input.value="Something" won't trigger a change event.


fireEvent(inputField, 'change');


input.value="Something"





Hey Juan! Your example doesn't define JSUtil.NodeTypes.DOCUMENT_NODE
– Kato
May 13 '11 at 21:52





I know that the question is about clicking events but you provided some generic code here and what I can see the change events are not going to be fired (I tested it and this does not really works for such events). To trigger change events I had to use jquery trigger function.
– Aleksander Lech
Feb 1 '16 at 16:58





@AleksanderLech Just firing an event does not guarantee that the action will take place. It does for click, it does not for change. The use case for events where change doesn't work is when you want to make a change to its value, but you want all the change event handlers to be called (whether they were set with jQuery or not). I can provide more meaningful help if you ask a new question with the exact code you were trying but wasn't working.
– Juan Mendes
Feb 1 '16 at 17:38


jQuery





Thanks for the fast response. I was able to get the change event running after few modifications to your snippet: 1) var node = document.getElementById(originalEvent.srcElement.id); 2) event.initEvent(eventName, true, true); //I don`t know why you disabled bubbling for change events. Please tell me what you think.
– Aleksander Lech
Feb 2 '16 at 9:47




What


l.onclick();



does is exactly calling the onclick function of l, that is, if you have set one with l.onclick = myFunction;. If you haven't set l.onclick, it does nothing. In contrast,


onclick


l


l.onclick = myFunction;


l.onclick


l.click();



simulates a click and fires all event handlers, whether added with l.addEventHandler('click', myFunction);, in HTML, or in any other way.


l.addEventHandler('click', myFunction);





FWIW this only works on an element level. If you add a click event to the window object, it won't magically expose a window.click function.
– James Donnelly
Mar 20 '17 at 10:42


window


window.click



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):


var l = document.getElementById('testLink');
for(var i=0; i<5; i++){
l.click();
}



This will generate the required result



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 or el.fireEvent where el will be your Anchor element. I believe both of these will require constructing an Event object to pass in.


el.dispatchEvent


el.fireEvent


el



The alternative, not entirely correct, quick-and-dirty way would be this:


var el = document.getElementById('anchorelementid');
el.onclick(); // Not entirely correct because your event handler will be called
// without an Event object parameter.



.click() does not work with Android (look at mozilla docs, at mobile section). You can trigger the click event with this method:


.click()


function fireClick(node){
if (document.createEvent) {
var evt = document.createEvent('MouseEvents');
evt.initEvent('click', true, false);
node.dispatchEvent(evt);
} else if (document.createEventObject) {
node.fireEvent('onclick') ;
} else if (typeof node.onclick == 'function') {
node.onclick();
}
}



From this post





I was trying jQuery's trigger click but found that it ends up calling the callback rather than dispatching actual event on the DOM. @manolo your method is correct.
– Akshay Gundewar
May 4 '17 at 9:07





".click() does not work with Android" Actually, the latest table says "Compatibility unknown".
– Gaurang Tandon
Jun 30 at 13:52


.click()



Fair warning:



element.onclick() does not behave as expected. It only runs the code within onclick="" attribute, but does not trigger default behavior.


element.onclick()


onclick="" attribute



I had similar issue with radio button not setting to checked, even though onclick custom function was running fine. Had to add radio.checked = "true"; to set it. Probably the same goes and for other elements (after a.onclick() there should be also window.location.href = "url";)


onclick


radio.checked = "true";


a.onclick()


window.location.href = "url";





Indeed, using onclick() would mean the event object will not be automatically defined by the browser, so common methods like event.stopPropagation()will also be undefined.
– Boaz
Feb 19 '15 at 9:37


onclick()


event


event.stopPropagation()



IE9+


function triggerEvent(el, type){
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
}



Usage example:


var el = document.querySelector('input[type="text"]');
triggerEvent(el, 'mousedown');



Source: https://plainjs.com/javascript/events/trigger-an-event-11/




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).


Would you like to answer one of these unanswered questions instead?

bI0q91eJZRL kCo,8rg jvwfiYvmDiViXP1ObpZTmEWg4WpgKySX EvKU,dY79vW,sQ
r0c1JZjFRqPZNGsVXdxGoqC9R8PYAVCAmL2h7s 0oQSodeNO MzU VPhXrvtmmRqOwX,Xsu2d5bMPx3F kky2I

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

List of Kim Possible characters