6

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.

1
  • 2
    in jquery it would be $('#link').trigger('click'); Commented Dec 13, 2010 at 7:34

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

For those who are too lazy to dig for the example ;-) developer.mozilla.org/en-US/docs/Web/Guide/Events/…
also, this may be useful to help identify when to use this code stackoverflow.com/questions/9847580/…
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();
}

example

3 Comments

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.
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
Works on FF under Windows
1

this should do the trick

document.getElementById('yourLink').click();

5 Comments

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, sometimes, we need more than a redirect on clicking a link :)
I wish I could use it. Forbidden in the product I'm working on.
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.
That link runs a ClickOnce (.NET) application. All I need to do - simulate a click on an existing link.
0
document.getElementById('mylink').click() 

1 Comment

There is no click method for a link object as far as I can remember.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.