luckydeng
luckydeng

Reputation: 95

How can I use JS to simulate the event of clicking a link in Chrome?

How can I use JS to simulate the event of clicking a link in Chrome?

I want the effect of autoclick.

Upvotes: 0

Views: 382

Answers (3)

Tasawer Khan
Tasawer Khan

Reputation: 6148

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 .

Upvotes: 0

Matt
Matt

Reputation: 75317

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.

Upvotes: 2

Ben S
Ben S

Reputation: 69342

Using jQuery:

$("a").click();

Will click all anchors on the page.

Upvotes: 0

Related Questions