Simulate anchor click with jQuery

I am trying to use jQuery to trick my browser into thinking that I clicked on an anchor. So when loads it has to click on the anchor (in the example below which will be redirected 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>

      

Until now, nothing happens haha.

+3


source to share


2 answers


How about calling the click

handler on the underlying DOM element:



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

      

+6


source


In JQuery, use the Trigger method :

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

};)

      



or simply

    a.trigger('click');

      

0


source







All Articles