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
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();
}
}
href attribute, this code will have no effect in Firefox (all versions).if(document.dispatchEvent) at all?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.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.
href attribute, this will only do what Josh states.
href? Fire event handlers on the link without navigating?