I need to simulate a click on a link using JavaScript. Could anybody tell me how it can be achieved? It should work in FireFox and IE.
Asked
Active
Viewed 1.5k times
6
-
2in jquery it would be `$('#link').trigger('click');` – mpen Dec 13 '10 at 07:34
4 Answers
4
As mentioned by others, you can use click
method for IE. For Firefox, have a look at element.dispatchEvent. See the example in the documentation.

dheerosaur
- 14,736
- 6
- 30
- 31
-
1For those who are too lazy to dig for the example ;-) https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events – Ash Feb 15 '17 at 00:13
-
also, this may be useful to help identify when to use this code http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser – Ash Feb 15 '17 at 00:16
4
var el = document.getElementById('link');
// Firefox
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, true);
el.dispatchEvent(event);
}
// IE
else if (el.click) {
el.click();
}

Anurag
- 140,337
- 36
- 221
- 257
-
That's strange. I don't have access to IE on a Mac, but it works on Firefox 3.6.13 for me. `click` is a standard method in IE, and I can't see why it shouldn't work in IE. Are you seeing any errors? Did you try the example link I posted below - http://jsfiddle.net/anurag/yP9y8/2/? How about other browsers like Chrome or Safari? Install Firebug for Firefox, or use Developer Tools in Chrome/Safari to see if any errors are showing up. – Anurag Dec 13 '10 at 08:41
-
There are no errors showing up. It just doesn't initiate the click. The same in the example code you've sent via jsfiddle.net – cycero Dec 13 '10 at 08:56
-
1
this should do the trick
document.getElementById('yourLink').click();

Jinesh Parekh
- 2,131
- 14
- 18
-
I believe ff does not understand click event on links. Could you wrap it up in a span and then simulate the click on it or try below: window.location.href = document.getElementById('yourLink').href ; – Jinesh Parekh Dec 13 '10 at 07:41
-
1@Jinesh, sometimes, we need more than a redirect on clicking a link :) – dheerosaur Dec 13 '10 at 07:48
-
1
-
could you tell me what else do you want to do when you trigger the click? You might be able to put that piece in a function and then directly call it rather than actually trigger the click. – Jinesh Parekh Dec 13 '10 at 08:22
-
That link runs a ClickOnce (.NET) application. All I need to do - simulate a click on an existing link. – cycero Dec 13 '10 at 08:23