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.
4 Answers
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.
2 Comments
Ash
For those who are too lazy to dig for the example ;-) developer.mozilla.org/en-US/docs/Web/Guide/Events/…
Ash
also, this may be useful to help identify when to use this code stackoverflow.com/questions/9847580/…
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();
}
3 Comments
Anurag
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 - 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.cycero
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
antonio
Works on FF under Windows
this should do the trick
document.getElementById('yourLink').click();
5 Comments
Jinesh Parekh
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 ;
dheerosaur
@Jinesh, sometimes, we need more than a redirect on clicking a link :)
cycero
I wish I could use it. Forbidden in the product I'm working on.
Jinesh Parekh
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.
cycero
That link runs a ClickOnce (.NET) application. All I need to do - simulate a click on an existing link.
document.getElementById('mylink').click()
1 Comment
Anurag
There is no
click method for a link object as far as I can remember.
$('#link').trigger('click');