6

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?

Maxx
  • 3,925
  • 8
  • 33
  • 38
  • Is that the actual rendered code? The snippet you gave seems pretty straight forward, I'm surprised that isn't working in Firefox. I'm guessing the bubbling event of the click is being stopped for Firefox somewhere. You can do alert(document.getElementById('myHrefLink').click) to see what is actually in the click event. (Note: the .click does NOT include the parathesis). – rkw Jul 27 '11 at 19:46
  • It comes up as undefined in firefox, and as a function in IE. Perhaps I should have mentioned this sooner, but this link is also inside an iframe. Having said that, it returns the reference to the a href element just fine, it seems more like firefox just doesn't think that click() is a function of the element. – Maxx Jul 27 '11 at 20:15
  • The above code is simplified from what I'm actually working with, of course, but I did copy and paste it into w3school's tryit editor in IE and FF to make sure I get the same results as I see in my more complex variation. http://www.w3schools.com/js/tryit.asp?filename=tryjs_write – Maxx Jul 27 '11 at 20:16

11 Answers11

4

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.

Boris Zbarsky
  • 34,758
  • 5
  • 52
  • 55
  • 1
    There's a Firefox 5? I'm still using Firefox 3. – Maxx Jul 28 '11 at 13:49
  • @Maxx Firefox 5 was released in late June, yes. If you're still using 3.6, then you're missing out. ;) – Boris Zbarsky Jul 28 '11 at 14:56
  • So I guess this will eventually start working on it's own? I suppose that works for me, it was only required to work in IE6 anyway (yea, someone still uses that). I was mostly curious about the specifics of the issue and I guess I have my answer now. – Maxx Jul 28 '11 at 16:12
  • Yeah, starting late September this will just work, at least for Firefox users that are up to date. – Boris Zbarsky Jul 28 '11 at 16:31
2

Here is my other answer. This will dynamically remove what is in the href, put "#" in the href, and add an onclick="" with "alert('Link was clicked')" in it.

Here's the code:

<script type="text/javascript">
$(document).ready(function() {
    $('#myHrefLink').attr({
        href: '#',
        onclick: 'alert("Link was clicked");return false;'
    });
});

function clickLinkDynamically() {
    $('#myHrefLink').trigger('click');
}
</script>

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

<br /><br />

<div style="padding:10px;border:2px solid grey;background-color:lightgrey;cursor:pointer;" onclick="clickLinkDynamically();">Click here to dynamically click on the link</div>

You can see it working here: http://jsfiddle.net/JVHEs/

I hope this helps.

Nathan
  • 11,814
  • 11
  • 50
  • 93
  • At this point I feel like I'm just being a downer, but this solution wouldn't work for me either. The problem is that this link has event handlers somewhere in the far reaches of code I don't have access to and it's not that any specific code has to happen but that the actual link has to be clicked. Otherwise I could just assign onclick="eval(this.href);" (for JS) or onclick="window.location=this.href" (for a link), unfortunately it is the act of clicking it that I need to figure out :( Perhaps I should just repost this question as a specific issue with the 3rd party software I'm using. – Maxx Jul 28 '11 at 13:54
  • That code clicks the link though. You can make the ordinary `My HREF Link` click by clicking the div. If you want to make the link click dynamically by itself, just put the `$('#myHrefLink').trigger('click');` right before the last `});` Is there something I'm not getting? That is working for me without altering the a tag or anything. By adding the script tag to your page it will click the link. I can edit the code so it automatically clicks the link if you wish. – Nathan Jul 28 '11 at 18:30
  • Let me try this one more time – Maxx Jul 28 '11 at 21:25
  • I tried this again, and it's a no go. a=$("iframe").contents().find(".plupload_start"); a.attr({ href: '#', onclick: 'alert("Link was clicked");return false;' }); a.trigger('click'); It acts as if nothing is going wrong, but for whatever reason the upload isn't starting (intended use case). Anyway, I'm told this is going to be fixed in upcoming versions of firefox and I only need it to work in IE, so I guess I'll leave it at that. I really appreciate all your assistance and the time you spent trying to help me out. – Maxx Jul 28 '11 at 21:35
  • @Maxx Glad I could help. Sorry that we couldn't get this to work, must just be a problem with Firefox? – Nathan Jul 28 '11 at 23:49
  • Yea, chrome as well. According to some other comments in this post, this is due to change with upcoming releases of firefox. I guess we'll see. – Maxx Aug 01 '11 at 13:28
2

The answer is that you cannot dynamically click on the href portion of a link in firefox or chrome at this time.

<a href="javascript:alert('This works!');">This does not work dynamically.</a>

VS

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

It seems that FireFox is only able to fire a click event on an HTML link when an onclick property is present. There are tons of workarounds for this so long as the link can be altered in some way (see most comments in this post), but as far as doing what I originally intended to, that only works in IE, currently.

http://jsfiddle.net/HVGre/1/ - see failed results here.

Maxx
  • 3,925
  • 8
  • 33
  • 38
1

This should work, even in Firefox. Perhaps the issue is you are calling the .click before the DOM is ready. JQuery has a nice method for this:

$(document).ready(function() {
    $("#myHrefLink").click();
});

In non JQuery your best bet is:

window.onload = function () {
    document.getElementById("myHrefLink").click();
}

This may not be the issue, but not sure what else it could be...

Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
  • I agree, it really SHOULD work, but it is not, for me. I just tested the above code and it works in IE but not firefox... Firebug tells me that [document.getElementById("myHrefLink").click is not a function] sigh.... maybe it's time for a reboot? – Maxx Jul 27 '11 at 20:24
  • Unfortunately rebooting didn't work. It seems like an actual issue afterall. Have any of you tested this yet? I can't be the only one who this is broken for. Just try clicking a link on any page using firebug. – Maxx Jul 27 '11 at 20:37
  • if I go to http://www.jQuery.com and run $("a")[0].click(); or $($("a")[0]).trigger("click"); in firebug, it does not work. – Maxx Jul 27 '11 at 20:40
1

This works most of the time

function callClickEvent(element){
    var evt = document.createEvent("HTMLEvents"); 
    evt.initEvent("click", true, true); 
    element.dispatchEvent(evt);
}

callClickEvent(document.getElementById("myElement"));

EDIT:

and here's the other one I always loose

function callClickEvent2(element){
    var evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
    element.dispatchEvent(evt);
}

callClickEvent2(document.getElementById("myElement"));

my pastebin for this: http://pastebin.com/VMHvjRaR

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
1

I think you're going to have to use jQuery, as jQuery is working for me:

<script type="text/javascript">
function clickLinkDynamically() {
    $('#myHrefLink').click();
}
</script>

<a href="#" onclick="alert('Link was clicked');return false" id="myHrefLink">My HREF Link</a>
<br /><br />
<div style="padding:10px;border:2px solid grey;background-color:lightgrey;cursor:pointer;" onclick="clickLinkDynamically();">Click here to dynamically click on the link</div>

You can see an example in jsFiddle: http://jsfiddle.net/7vCmj/

Maybe it wasn't working because you didn't have type="text/javascript" in?

I hope this helps.

Nathan
  • 11,814
  • 11
  • 50
  • 93
  • Your example works, however it works because the link has an onclick event. Unfortunately my original link (which cannot be altered by me) does not :( I think this is the source of the problem here. Browsers that actually follow standards don't see the href portion of the link as something that can be clicked, it seems like. While this doesn't solve my issue, I do feel it is an important clue, and for that I thank you! – Maxx Jul 28 '11 at 00:54
  • @Maxx I see what you mean now. The reason why it isn't working is because it is inside the href. But I think I do have a solution for that! You can dynamically add an onclick to the A tag and then remove the href contents dynamically. (You wont have to edit it or anything) I'll post it as another answer. – Nathan Jul 28 '11 at 04:25
  • @Maxx I posted it. See my answer above. :) – Nathan Jul 28 '11 at 05:12
0

Here's another solution that takes all links on the page and converts them to use the click event unobtrusively. Essentially turning

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

into

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

Enjoy:

$('a[href^="javascript:"][href!="javascript:;"]').each(function () {
    var oldHref = $(this).prop('href').substring(11);
    try {
        $(this).click(new Function('e', oldHref + ';e.preventDefault();')).prop('href', '#');
    }
    catch (err) {}
});

$('#myHrefLink').click();
Jeff the Bear
  • 5,603
  • 3
  • 22
  • 18
0

Try this

$(document).ready(function(){
    $('#myHrefLink').click(function(){
        alert('!');
    });


   //To trigger click dynamically use
   $('#myHrefLink').trigger('click');
}
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • While this solution does work in the context of this example, I do not want to change the original functionality of the href link as it triggers some custom functionality that I do not have access to modify or look at. Strangely, simply using the jQuery trigger function does not appear to work or cause any errors. – Maxx Jul 27 '11 at 19:40
0

Try this instead, add reference to jQuery file first.

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

<script>$("#myHrefLink").trigger("click");</script>
-1

Why don't you just do this? (Unless I am missing something)

$('#myHrefLink').click(function(){
    alert('!');
});
Phil
  • 10,948
  • 17
  • 69
  • 101
  • this adds a handler to the link which is activated onClick, it does not click the link dynamically, which is what I am looking for. – Maxx Jul 27 '11 at 19:27
-1

It's not clear what you are trying to achieve here, but as you can use jQuery, try this:

<a href="" id="myHrefLink">blah blah</a>

To TRIGGER a click:

 $('#myHrefLink').trigger('click');
Dunhamzzz
  • 14,682
  • 4
  • 50
  • 74
  • I am trying to click the link dynamically, without actually clicking on it with the mouse. – Maxx Jul 27 '11 at 19:29
  • It REALLY seems like this should work. I was very hopeful, but it does not in FF. I tested it in w3school's tryit editor – Maxx Jul 27 '11 at 20:18
  • Have you used duplicate IDs or anything like that? Javascript errors? – Dunhamzzz Jul 27 '11 at 20:19
  • Interestingly, it does not work in IE either with the above code, however it does with the original code I posted in the question. – Maxx Jul 27 '11 at 20:19
  • No, no duplicate IDs or anything. I'm testing it with a clean slate using the code written here. – Maxx Jul 27 '11 at 20:20
  • http://jsfiddle.net/HVGre/ Same result. Cool site though, thanks for pointing me to it. At least some good came of this post. – Maxx Jul 27 '11 at 21:13