1

So I have this html

<a class='test' href='somewhere' target='_blank'>Click me </a>

and I was expecting this jQuery selector to click it

I tried both the following and the new tab is not opening in Chrome

$('.test').click()
$('.test').trigger('click')
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • 2
    What you have should work fine, assuming you've included jquery.js and are running in a document.ready handler. Have you checked the console for errors? – Rory McCrossan Oct 09 '13 at 13:35
  • 1
    How are you running that code? It might be getting blocked as a unrequested popup window. Effectively trying to create a window without user input is generally frowned upon so I can imagine that if that is not in a click handler then the browser might decide you are doing things the user almost certainly doesn't want and not do it. – Chris Oct 09 '13 at 13:38
  • I dont want a new window but a new tab – Matt Elhotiby Oct 09 '13 at 13:49

4 Answers4

3

jQuery .click() and .trigger('click') only work to kick off any event handlers that are attached to the click event. It won't actually click the link and take you to the href.

andi
  • 6,442
  • 1
  • 18
  • 43
  • Here is a [fiddle](http://fiddle.jshell.net/Fw8Vj/) to show the event handler being kicked off by the $(".test").click() – Fabricio Oct 09 '13 at 14:24
2

Try

Wrap your code in $(document).ready(function(){...}

$(document).ready(function(){
    $('.test').click();
});

Update

Read Open a URL in a new tab (and not a new window) using JavaScript

.click() and .trigger('click') will execute the functions which are attached to the click event.

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
1

What you actually want to do is via jQuery open another window/tab on click. Like Andi said in their answer .click() and .trigger('click') merely trigger the handlers and don't represent an actual click on the page. Use:

window.open($('.test').attr('href'));

See Fiddle. Clicking on 'Click me' opens the stackoverflow link

However, some browsers will block this request as popup, so it is best to have it result from a user actually interacting with the page.

Zoe
  • 27,060
  • 21
  • 118
  • 148
ediblecode
  • 11,701
  • 19
  • 68
  • 116
  • 1
    It should be noted as well that if you just run that line of code in a `document.ready` then in chrome at least the popup blocker will block it unless you tell it not to so you have to be careful about where you open new windows from (eg automated events versus human instigated events). – Chris Oct 09 '13 at 15:36
-1

As Andi said in their answer the click injection will not actually click the link but will kick off the element click event. So, this could be a workaround solution:

$('.test').click( function () {
    window.open($(".test").attr("href"));
});

$('.test').click();

And the fiddle

Zoe
  • 27,060
  • 21
  • 118
  • 148
Fabricio
  • 839
  • 9
  • 17