tags:

views:

238

answers:

3

Hi, I'm just wondering how I can have javascript simulate a click on a element.

Currently I have

<script type="text/javascript">
function simulateClick(control)
{
    if (document.all)
    {
        control.click();
    }
    else
    {
        var evObj = document.createEvent('MouseEvents');
        evObj.initMouseEvent('click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
        control.dispatchEvent(evObj);
    }
}
</script>

<a href="http://www.google.com" id="mytest1">test 1</a><br>

<script type="text/javascript">
    simulateClick(document.getElementById('mytest1'));
</script>

But it's not working :(

Any ideas?

+3  A: 

Have you considered using jQuery to avoid all the browser detection? With jQuery, it would be as simple as:

$("#mytest1").click();
BradBrening
A: 

"Five Most Common Coding Errors": http://javascript.about.com/od/hintsandtips/a/worst_4.htm

Just about no one runs IE4 any more and so support for the document.all DOM is no longer required. It is really surprising though how namy people still use it in their coding. Worse is that support for the document.all DOM is often tested for in order to determine the browser being used and if it is supported then the code assumes that the browser is Internet Explorer (which is completely wrong usage since Opera also recognises that DOM).

zaf
+1  A: 

Here's what I cooked up. It's pretty simple, but it works:

function eventFire(el, etype){
  if (el.fireEvent) {
    (el.fireEvent('on' + etype));
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}
KooiInc