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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
cycero
  • 93
  • 1
  • 2
  • 4

4 Answers4

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
  • 1
    For 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();
}

example

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
  • Works on FF under Windows – antonio Dec 28 '14 at 19:20
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
    I wish I could use it. Forbidden in the product I'm working on. – cycero Dec 13 '10 at 08:19
  • 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
0
document.getElementById('mylink').click() 
Bhanu Prakash Pandey
  • 3,805
  • 1
  • 24
  • 16