tags:

views:

185

answers:

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

+3  A: 

If you use jQuery...

$('a#myLinkID').click();
a432511
+1  A: 

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.

CMS
I don't believe that .click() is cross-browser when used outside of jQuery
a432511
You're right, it's onclick, was a typo :)
CMS
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
Yes, haven't noticed that the OP explicitly required to avoid navigation...
CMS
There you are. I can verify this code navigates to the link in chrome, opera. However IE + FF do work.
Roatin Marth