3

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.

Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
  • 3
    Why not just use [a.click()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click) – Patrick Evans Apr 26 '15 at 20:58
  • 1
    @PatrickEvans Because it will not trigger native click and browser will not navigate to new address. – dfsq Apr 26 '15 at 20:59
  • @dfsq, is this browser dependent, as doing a `.click()` on an anchor element does a page navigation in my Chrome browser. – Patrick Evans Apr 26 '15 at 21:02
  • @PatrickEvans Are you sure? Browser should not matter, as jQuery trigger basically just triggers "own" events bound with `on` method, as far as I know. http://plnkr.co/edit/dD7Cm6BnnWeEcWAke0pM?p=preview – dfsq Apr 26 '15 at 21:04
  • Your example works for me http://jsfiddle.net/j08691/6vwp3qwj/. Are you getting errors in the console? Do you need jQuery for this? – j08691 Apr 26 '15 at 21:04
  • 1
    `a.click()` works fine. Isn't it working for you because you are calling `simulateClick()` before page load? – Ruslanas Balčiūnas Apr 26 '15 at 21:04
  • @dfsq, that sample is doing the jQuery's click event, the OP's `a` variable is the DOM element, so .click would be the DOM elements click – Patrick Evans Apr 26 '15 at 21:05
  • @dfsq difference in OP code is dom element not jQuery object – charlietfl Apr 26 '15 at 21:05
  • @PatrickEvans ops, of course, I though you were talking about jQuery. Native `click` works of course. – dfsq Apr 26 '15 at 21:07
  • @j08691 I'm confused, your JSFiddle works but when I change the html so that the anchor goes to say google.com it doesnt work? – Albert Renshaw Apr 26 '15 at 21:11
  • 1
    That's just a browser security setting (`Refused to display 'https://www.google.com/?gws_rd=ssl' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.`) – j08691 Apr 26 '15 at 21:12

2 Answers2

5

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

function simulateClick() {
    var a = $(".GoogleAnchor")[0];
    a.click();
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

In JQuery use the Trigger method:

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

};)

or just

    a.trigger('click');
MaxRocket
  • 920
  • 1
  • 12
  • 26