user189598
user189598

Reputation:

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

Upvotes: 1

Views: 5887

Answers (3)

Clark
Clark

Reputation: 1036

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

Upvotes: 3

o.k.w
o.k.w

Reputation: 25810

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>

Upvotes: 0

Josh Stodola
Josh Stodola

Reputation: 82483

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();
  }    
}

Upvotes: 7

Related Questions