The following function triggers a mouseclick event on the DOM-node you pass to it.
I’ve tested it with Internet Explorer 6, 7, 8 and 9, Firefox 3.x and 11 nightly. Chrome 17-dev, Opera 10 and 11, webkit on iOS 5 iPhone 4, webkit on Android 2.3.4, Safari 4.0.5 on Windows. If you need it on another browser/version/os, please test it and post the result as a comment here.
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(); } } |
Example usage:
//assumes <a href="http://www.nonobtrusive.com" id="myLink">Click me</a> var theNode = document.getElementById('myLink'); theNode.onclick = function(){ alert("You clicked a link with href:" + this.href); }; fireClick(theNode); |
#1 by Naddt19 on August 31, 2012 - 8:26 am
It would be too good if you could give explanation of the code