KnowlegeZone.com, Share knowledge Gain knowledge
     

Home > JavaScript : Force links to open in new window

Article By: Saqib   Date: 8/19/2008

Force links to open in new window

Sometimes you have  content which contains Anchor Tag (A) and you would like to open its Src attribute within a "new" window instead of opening it in the Same window. Script below will let you open all the Ancor tags with the "target=_blank" attribute in it. 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head>

<title>Untitled Page</title>

<script>

function openTarget() {

var getDiv = document.getElementById("selfing")

var getDivA = getDiv.getElementsByTagName("a")

for(i=0; i<getDivA.length; i++) {

getDivA[i].target="_blank"

}

}

</script>

</head>

<body onload="openTarget()">

<form id="form1" runat="server">

<a href="http://www.msn.com">Same window</a>

<div id="selfing">

<a href="http://www.yahoo.com">New window</a><br />

<a href="http://www.yahoo.com">New window2</a>

</div>

</form>

</body>

</html>

 

Please note, Code above targets only a "DIV" name "selfing" within the entire page content.


Share |

Comments.
Comment/Solution Posted By: pavan kumar    Date: 9/8/2008 2:19:00 AM
good one....

Comment/Solution Posted By: khan    Date: 9/8/2008 2:05:00 PM
Actually it will Force links to open in new window within a Div.

Comment/Solution Posted By: khan    Date: 9/26/2008 4:00:00 AM
Now I can Force links to open in new window.

Sweet

Comment/Solution Posted By: Saqib    Date: 10/4/2008 3:26:00 AM
Note:Using target="_blank" in an html page will mean that it will not validate using W3C

so here is another solution if you need to validate it for w3c.

1) Replace all instances of target="_blank" with rel="external" (or whatever you prefer)

2) Insert this javascript in the page header:


function externalLinks() {
if (!document.getElementsByTagName) return;
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++) {
var anchor = anchors[i];
if (anchor.getAttribute("href") &&
anchor.getAttribute("rel") == "external")
anchor.target = "_blank";
}
}
window.onload = externalLinks;


Pages :
Post Comment or Solution   OR   Sign in using Google/Aol/Yahoo/Msn/OpenID
Your Name:  
Your Email:  
Comments:
 
Please Verify:
(Type Answer)