Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I click an href link dynamically in firefox? Expected approach only works in IE

http://jsfiddle.net/HVGre/1/ - test link.


I have an html link on my page that I need to be able to click dynamically. This works fine with the .click() function in IE, but fails in firefox. I cannot change the link to a button, so that is not an option, it has to be an href.

<a href="javascript:alert('!');" id="myHrefLink">My HREF Link</a>

<script>
   document.getElementById("myHrefLink").click();
</script>

Is there a good workaround for this in firefox? I'm able to use jQuery if that opens any possibilities.

  1. I do not intend to assign an event handler to the link, I simply need to click the link dynamically using javascript (without doing so manually with the mouse).

  2. I cannot alter the functionality of the original link. It has to remain as it is.


EDIT:

It seems that the issue Firefox has with this code is that the link does not have an onclick event and has the code referenced via the href, or otherwise NOT onclick (in the example here the code is on href, in my actual code the href is set to just '#', however the link somehow triggers other actions when clicked, don't ask me how, it's a weird flash integration with the plupload tool).

<a href="javascript:alert('This works!');">Click me dynamically</a>

VS

<a href="#" onclick="alert('This works!');">Click me dynamically</a>

The second example is solid and works in all browsers when the click() function is triggered, however I need the first of these two to work without changing the link dynamically or otherwise. Any clever ideas?

like image 356
Maxx Avatar asked Jul 27 '11 19:07

Maxx


1 Answers

The behavior here depends on the exact Firefox version:

  1. Firefox 4 and earlier does not have a click() method on anchors at all.
  2. Firefox 5 and 6 do have such a method, and the method dispatches an untrusted click event, but they do not allow untrusted events to trigger a link's href.
  3. Firefox 7 and later allow untrusted click events to trigger a link.

So your options are to wait until late September when Firefox 7 ships, or if you need to support earlier versions to not use .click() to trigger links. Getting the .href of the link and then setting the relevant window's location to that string should work as a workaround.

like image 166
Boris Zbarsky Avatar answered Sep 18 '22 23:09

Boris Zbarsky