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

1
  • 2
    What do you want to accomplish? Navigating to the page in the href? Fire event handlers on the link without navigating? Commented Nov 12, 2009 at 15:19

3 Answers 3

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();
  }    
}
Sign up to request clarification or add additional context in comments.

5 Comments

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).
Thanks, Crescent Fresh. I can't test on FF right now. Does it fall through the if(document.dispatchEvent) at all?
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: 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 stackoverflow.com/questions/809057/… IMO it's just a bug.
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.
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

2 Comments

FYI: This only fires the function assigned to the click event.
Yes, depending on if the OP wants to actually navigate to the page specified in the href attribute, this will only do what Josh states.
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>

Comments

Your Answer

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