2

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet Explorer

Thanks

2 Answers2

4

With plain JavaScript it depends on how do you bind the event, if you assigned an anonymous function to the onclick attribute of the element, you can simply:

var link = document.getElementById('linkId');
link.onclick();

If you used addEventListener or attachEvent (for IE) you should simulate the event, using the DOM Level 2 Standard document.createEvent or element.fireEvent (for IE).

For example:

function simulateClick(el) {
  var evt;
  if (document.createEvent) { // DOM Level 2 standard
    evt = document.createEvent("MouseEvents");
    evt.initMouseEvent("click", true, true, window,
      0, 0, 0, 0, 0, false, false, false, false, 0, null);

    el.dispatchEvent(evt);
  } else if (el.fireEvent) { // IE
    el.fireEvent('onclick');
  }
}

Check the above example here.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • I don't believe that .click() is cross-browser when used outside of jQuery – a432511 Nov 13 '09 at 04:19
  • WRT links (as the q asks) `dispatchEvent` *will* navigate (as the OP does not want) in non-buggy w3c-compliant browsers. See my comment to http://stackoverflow.com/questions/1722593/browser-friendly-way-to-simulate-anchor-click-with-jquery – Crescent Fresh Nov 13 '09 at 09:35
  • There you are. I can verify this code navigates to the link in chrome, opera. However IE + FF do work. – Roatin Marth Nov 13 '09 at 17:48
2

If you use jQuery...

$('a#myLinkID').click();
a432511
  • 1,907
  • 4
  • 26
  • 48