I\'m just wondering how I can use JavaScript to simulate a click on an element.
Currently I have:
The top answer is the best! However, it was not triggering mouse events for me in Firefox when etype = 'click'
.
So, I changed the document.createEvent
to 'MouseEvents'
and that fixed the problem. The extra code is to test whether or not another bit of code was interfering with the event, and if it was cancelled I would log that to console.
function eventFire(el, etype){
if (el.fireEvent) {
el.fireEvent('on' + etype);
} else {
var evObj = document.createEvent('MouseEvents');
evObj.initEvent(etype, true, false);
var canceled = !el.dispatchEvent(evObj);
if (canceled) {
// A handler called preventDefault.
console.log("automatic click canceled");
} else {
// None of the handlers called preventDefault.
}
}
}