0

Let's say I have a single HTML page and it contains hundreds of links. These links will load in the same window when anybody clicks them.

I want it to open in another window. I know that I can use target for each link:

<a href="http://www.example1.com/" target="_blank">My Text1</a>
<a href="http://www.example2.com/" target="_blank">My Text2</a>
<a href="http://www.example3.com/" target="_blank">My Text3</a>

Howeder, I'd prefer to use JavaScript if that's possible. Is it possible to do that with JavaScript, and if so, how?

icktoofay
  • 126,289
  • 21
  • 250
  • 231
user2203703
  • 1,955
  • 4
  • 22
  • 36

3 Answers3

1

Yes, it is. Use something like this:

var newtab = window.open('http://www.example1.com/', '_blank');

newtab.focus();

This may open in new tabs or new windows depending on the particular browser, but I don't know of a way to control that any more specifically.

EDIT Or were you asking for a way to set the behavior for all links on the page? Then you can add the proper target to all of them when the page loads.

With jQuery: http://jsfiddle.net/b8hdv/

$(document).ready(function() {
    $('a').attr('target', '_blank');
});

...or without jQuery: http://jsfiddle.net/uFvUS/

window.onload = function(e) {
    var links = document.getElementsByTagName('a');

    for (var i = 0; i < links.length; i++) {
        links[i].target = '_blank';
    }
}
metadept
  • 7,831
  • 2
  • 18
  • 25
  • Yes, for all links on the page..i have tried your codes,but it doesn't work..could you check it again please ? thanks – user2203703 Mar 30 '13 at 02:28
  • If there is no "target" for my current links `My Text1` ..can this work for me? – user2203703 Mar 30 '13 at 02:42
  • @user2203703 you'll need to run the script when the page is done loading (if you're not already). I edited my solution to include the wrapper functions; see if that works. – metadept Mar 30 '13 at 02:54
  • @user2203703 sorry, I forgot to close the function. Also you should use jsfiddle's dropdown stuff on the left to import libraries (see the examples I added). Hope this helps! – metadept Mar 30 '13 at 03:10
0
function open_in_new_tab(url )
{
  var win=window.open(url, '_blank');
  win.focus();
}

Use like this:

$("#a_id").on("click", function(){
open_in_new_tab($(this).attr("href"));
});

Demo HTML:

<a href="somepage.html" id="a_id">Click me!</a>

Found here

Community
  • 1
  • 1
What have you tried
  • 11,018
  • 4
  • 31
  • 45
0

Try this:

window.open('http://www.example1.com');

and capture the event click.