1

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?

Thanks

  • 2
    What do you want to accomplish? Navigating to the page in the `href`? Fire event handlers on the link *without* navigating? – Crescent Fresh Nov 12 '09 at 15:19

3 Answers3

7
window.onload = function() {
  var myLink = document.getElementById("YOUR_A_TAG_ID");
  fireClick(myLink);
};

function fireClick(elem) {
  if(typeof elem == "string") elem = document.getElementById(objID);
  if(!elem) return;

  if(document.dispatchEvent) {   // W3C
    var oEvent = document.createEvent( "MouseEvents" );
    oEvent.initMouseEvent("click", true, true,window, 1, 1, 1, 1, 1, false, false, false, false, 0, elem);
    elem.dispatchEvent( oEvent );
  }
  else if(document.fireEvent) {   // IE
    elem.click();
  }    
}
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
  • FYI, *if* the goal of the OP is to navigate to the page specified in the `href` attribute, this code will have no effect in Firefox (all versions). – Crescent Fresh Nov 12 '09 at 15:21
  • Thanks, Crescent Fresh. I can't test on FF right now. Does it fall through the `if(document.dispatchEvent)` at all? – Josh Stodola Nov 12 '09 at 15:33
  • Or does FireFox simply disallow this behavior on HTML anchors? Any documentation? I can see how it would be perceived as a semi-security risk. – Josh Stodola Nov 12 '09 at 15:34
  • @Josh: yes, the `document.dispatchEvent` code path will definately be hit, and all the usual "fire event handlers", "bubble and repeat" will happen (as you've specified it should). It's just that Firefox simply doesn't then navigate to the page. See http://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-firefox/809611#809611 IMO it's just a bug. – Crescent Fresh Nov 12 '09 at 15:42
  • A potential (ugly) hack would be to check to see if the window.unload event fires after attempting to programmatically dispatch the click event. If not, set location.href to the anchor href. Far from ideal, but it could work. – Josh Stodola Nov 12 '09 at 18:00
3

With JQuery It would be like this.

$("#YOUR_A_TAG_ID").click();

This only fires the function assigned to the click event. It will not navigate to the path specified in the href attribute.

JQuery documentation for click

Clark
  • 1,006
  • 8
  • 14
0

Another way is using JQuery's trigger feature.

<span onmouseover="$('#alink').trigger('click');">Hello World</span>

<a href="http://someurl" id="alink">A Link</a>
o.k.w
  • 25,490
  • 6
  • 66
  • 63