user1137778
user1137778

Reputation: 1151

Javascript to click on href link

I got this code after searching around on stack overflow and it should work, but for some reason I am getting an error. I am trying to write JS that simulates a user clicking on a specific href link that has a specific ID.

This needs to work in all the major browsers (chrome, FF, IE, Safari)

here is the code:

HTML:

<a id="clickhere" href="http://link.com">Need to simulate user clicking on this link</a>

JS:

fireOnclick();
function fireOnclick() {
var target=document.getElementById("clickhere");
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, target[0]);
    target[0].dispatchEvent( oEvent );
    }
else if(document.fireEvent) { // IE
    target[0].fireEvent("onclick");
    }    
}

Any help is appreciated. Thanks

Upvotes: 0

Views: 1506

Answers (1)

Commissioner Gordon
Commissioner Gordon

Reputation: 358

You need to remove the [0] from your target[0] references. getElementById returns an element, not an array of elements. I tested in Chrome and it worked fine.

http://jsfiddle.net/mendesjuan/vCVbA/1/

Upvotes: 4

Related Questions