3

I have a link that opens in a new tab with _blank:

<a href="new_page.html" target="_blank">link</a>

I'd like to be able to 'click' on this from Javascript. I know I could do document.location=... but the problem here is the new tab part. Is this possible?

izb
  • 50,101
  • 39
  • 117
  • 168
  • If you just want to click on the link in Javascript, there are certainly ways. If you want to open a new tab using javascript alone, you may be interested in this question: http://stackoverflow.com/questions/7924232/open-new-tab-in-javascript – NT3RP Nov 17 '11 at 00:39

4 Answers4

4

You can usually open a new window or tab using window.open. So instead of setting location, just call window.open and pass only the URL, nothing else.

Ry-
  • 218,210
  • 55
  • 464
  • 476
1
$("#your_a").click(function(e) {
   e.preventDefault();
   window.open($(this).attr("href"), this.target);
}

You could use any name for target, preventDefault() if you want to override the link actions completely

0

If you really want to simulate click, you can give a id to the anchor tag and call jQuery click() on that element.

<a id="mylink" href="new_page.html" target="_blank">link</a>

and in script

$("#mylink").click()
R G
  • 111
  • 5
0

to "simulate" the click you trigger the click event:

HTML:

<a href="new_page.html" target="_blank" id="mylink">click me</a>

jQuery:

$("#mylink").trigger("click");

-or-

$("#mylink").click();

Using 'trigger' allows you to pass in extra parameters if you bind a function to the click event. See the jQuery 'trigger' documentation for more info: http://api.jquery.com/trigger/