Albert Renshaw
Albert Renshaw

Reputation: 17882

Simulate clicking an anchor with jQuery

I'm trying to use jQuery to trick my browser into thinking I clicked on the anchor. So when the loads it should click the anchor (in the example below that will redirect to google.com)

<a class="GoogleAnchor" href="google.com">Click Me</a>

<script>

function simulateClick() {
    var a = $(".GoogleAnchor")[0];
    var e = document.createEvent("MouseEvents");
    e.initEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    a.dispatchEvent(e);
}

simulateClick();

</script>

So far nothing happens haha.

Upvotes: 3

Views: 202

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

How about calling the click handler on the underlying DOM element:

function simulateClick() {
    var a = $(".GoogleAnchor")[0];
    a.click();
}

Upvotes: 5

MaxRocket
MaxRocket

Reputation: 992

In JQuery use the Trigger method:

a.trigger('click', function(){
 // if you want a callback function

};)

or just

    a.trigger('click');

Upvotes: 0

Related Questions