views:

55

answers:

3

How to use JS to simulated a event of click a link on chrome?

I want the effect of autoclick.

A: 

Using jQuery:

$("a").click();

Will click all anchors on the page.

Ben S
A: 

you can do this by Simply writing this.

document.getElementById("yourLinkID").onclick()

Here is another way to do that.

var fireOnThis = document.getElementById('someID');
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent( 'click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null );
fireOnThis.dispatchEvent(evObj);

For more details search "Manually firing events" in This article .

Taz
This will not work in Firefox, Chrome, Opera and Safari. Only IE will work.
Ben S
@ben works fine in firefox and chrome. http://jsbin.com/awuba4/edit
lincolnk
A: 

It depends what you mean by "simulate".

If you want to change page url,

window.location.href = document.getElementById("yourAHref").href;

or with jQuery:

window.location.href = $('yourAnchorSelector').attr('href');

If you want to simulate the clicking of the event, you will have to use fireEvent or dispatchEvent, depending on the browser:

jQuery makes this easy by:

$('yourAnchorSelector').trigger('click');

But will only trigger events that have been bound through jQuery.

Matt