views:

1640

answers:

6

In IE, I can just call element.click() from javascript - how do I accomplish the same task in Firefox? Ideally I'd like to have some javascript that would work equally well cross-browser, but if necessary I'll have different per-browser javascript for this.

A: 

have you seen http://seleniumhq.org/projects/ide/ ?

l0st3d
thanks, yes; I've seen selenium. Unfortunately it requires a browser extension, which is not possible in some mobile testing scenarios.
Bruce
+7  A: 

Using jQuery you can do exactly the same thing, for example:

$("a").click();

Which will "click" all anchors on the page.

jakemcgraw
+2  A: 

element.click() is a standard method outlined by the W3C DOM specification. Mozilla's Gecko/Firefox follows the standard and only allows this method to be called on INPUT elements.

apphacker
Understood, but not helpful when I want to programmatically simulate clicks on non-INPUT elements.
Bruce
+3  A: 

Are you trying to actually follow the link or trigger the onclick? You can trigger an onclick with something like this:

var link = document.getElementById(linkId);
link.onclick.call(link);
jiggy
interesting, I'll give that a try. This is part of a testing harness, so we don't know ahead of time what specific element we are going to be clicking on - it is whatever the test case specifies.
Bruce
You don't need to specify a context; since onclick is a property of 'link' the context will already be set appropriately.
J-P
+2  A: 

Here's a cross browser working function (usable for other than click handlers too):

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
+4  A: 

For firefox links appear to be "special". The only way I was able to get this working was to use the createEvent (described here: https://developer.mozilla.org/en/DOM/document.createEvent) and call the initMouseEvent function. Even that didn't work completely, I had to manually tell the browser to open a link...

var theEvent = document.createEvent("MouseEvent");
theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var element = document.getElementById('link');
element.dispatchEvent(theEvent);

while (element)
{
    if (element.tagName == "A" && element.href != "")
    {
        if (element.target == "_blank") { window.open(element.href, element.target); }
        else { document.location = element.href; }
        element = null;
    }
    else
    {
        element = element.parentElement;
    }
}
will