Elod P Csirmaz’s Blog: December 2009

7 December 2009

Triggering a click event

One would think that to simulate a click event on a link, one would only have to call OBJECT.onclick(). However, apart from not following the URL set in the HREF, this does not seem to trigger event handlers that are not in the actual inline onclick handler, but have been attached to the object later. There is, however, another solution that does this:

function doEventDispatch() {
var evt = null,
elm = null;

if(document.getElementById) {
elm = document.getElementById('test');
}
if(document.createEvent) {
evt = document.createEvent('MouseEvents');
}
if(elm && elm.dispatchEvent && evt && evt.initMouseEvent) {
evt.initMouseEvent(
'click',
true, // Click events bubble
true, // and they can be cancelled
document.defaultView, // Use the default view
1, // Just a single click
0, // Don't bother with co-ordinates
0,
0,
0,
false, // Don't apply any key modifiers
false,
false,
false,
0, // 0 - left, 1 - middle, 2 - right
null); // Click events don't have any targets other than
// the recipient of the click
elm.dispatchEvent(evt);
}
}

(from a post by Michael Winter)


This still won't follow the URL set in the HREF attribute, so one might need to add

location.href=elm.href;