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?

3
  • Yeah, you can add target="_blank" with javascript. Commented Mar 30, 2013 at 2:18
  • 1
    A google search of your question title would have gotten you the same answers as below. Commented Mar 30, 2013 at 2:18
  • Exactly, I don't get how these answers aren't found before asking ... Commented Mar 30, 2013 at 2:19

3 Answers 3

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';
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, for all links on the page..i have tried your codes,but it doesn't work..could you check it again please ? thanks
If there is no "target" for my current links <a href="http://www.example1.com/">My Text1</a> ..can this work for me?
@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.
@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!
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

Comments

0

Try this:

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

and capture the event click.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.