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?
-
Yeah, you can add target="_blank" with javascript.user2193789– user21937892013年03月30日 02:18:11 +00:00Commented Mar 30, 2013 at 2:18
-
1A google search of your question title would have gotten you the same answers as below.nathancahill– nathancahill2013年03月30日 02:18:39 +00:00Commented Mar 30, 2013 at 2:18
-
Exactly, I don't get how these answers aren't found before asking ...What have you tried– What have you tried2013年03月30日 02:19:26 +00:00Commented Mar 30, 2013 at 2:19
3 Answers 3
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';
}
}
4 Comments
<a href="http://www.example1.com/">My Text1</a> ..can this work for me?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
Try this:
window.open('http://www.example1.com');
and capture the event click.
Comments
Explore related questions
See similar questions with these tags.