0

Ok, so I searched all over with no answer. Can someone explain why

does not work with .trigger('click')

<a id="openNew" href="http://www.example.org">Click me</a>

<script type='text/javascript'> 
    $(window).load(function(){
        $('#openNew').addClass("external").attr({ target: "_blank", href: 'http://www.google.com' }).trigger('click');
    });
</script>

and it does not work with .click()

<script type='text/javascript'> 
    $(window).load(function(){
        $('#openNew').addClass("external").attr({ target: "_blank", href: 'http://www.google.com' }).click();
    });
</script>

Does not click the link whatever I do. It only works if I click it. How can I make it auto click? Working on this for about 1 hour and is driving me crazy, I know I'm must be doing something stupid.

JsFiddle for your convenience.

I wouldn't mind any other solution in plain JavaScript.

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
Mihai Iorga
  • 39,330
  • 16
  • 106
  • 107
  • This is a duplicate question. You're asking how to simulate a click of an anchor tag using jquery click/trigger. [Here is a previous post with your answer.](http://stackoverflow.com/questions/4482074/how-to-use-jquery-trigger-anchors-default-click-event) – kasdega Sep 01 '11 at 07:32
  • [JsFiddle](http://jsfiddle.net/H2KuF/9/) Showing that the click even is being triggered. – kasdega Sep 01 '11 at 07:35

4 Answers4

1

Use elem[0].click(); instead of elem.click(); since you want to call the native click function and not just trigger the click event.

By the way: Popup blockers will prevent this from actually opening a new window (luckily).

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

Simulating a user physically clicking the link is not possible. Since you are using target='_blank' I presume you want a new window? So you'll need to use window.open. Which popup blockers wont like.

kmcc049
  • 2,783
  • 17
  • 13
0

Actually it's clicked, but not opened link.. check out here http://jsfiddle.net/H2KuF/5/

Probably you need to open new browser window with this link from JS.

here is samples I found:

function open2(url, opt){
  if (opt == 0) // current window
    window.location = url;
  else if (opt == 1) // new window
    window.open(url);
  else if (opt == 2) // background window
    {window.open(url); self.focus();}
}
Samich
  • 29,157
  • 6
  • 68
  • 77
  • Basically this answer is correct. The click event is being triggered it just isn't doing what you think it should do. – kasdega Sep 01 '11 at 07:34
0

Karl swedberg states here (One of the comments)

Using .trigger('click') will not trigger the native click event.

Doing the following will work:

<a id="openNew" href="http://www.example.org">Click me</a>

<script type='text/javascript'>
    $(window).load(function(){
        $('#openNew').addClass("external").attr({ target: "_blank", href: 'http://www.google.com' })[0].click();
    });
</script>

Demo here

Tomgrohl
  • 1,767
  • 10
  • 16