Tuesday, March 1, 2011

How to click a link from javascript

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

From stackoverflow
  • 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();
      }    
    }
    
    Crescent Fresh : 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).
    Josh Stodola : Thanks, Crescent Fresh. I can't test on FF right now. Does it fall through the `if(document.dispatchEvent)` at all?
    Josh Stodola : 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.
    Crescent Fresh : @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.
    Josh Stodola : 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.
  • 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

    Josh Stodola : FYI: This only fires the function assigned to the click event.
    Crescent Fresh : 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.
  • 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>
    

0 comments:

Post a Comment