At times you may need to launch certain links into a new window. The ‘target’ attribute is deprecated and is therefore not allowed when using XHTML with a strict doctype. Using this script, you will be able to keep your pages valid while also using the target attribute to open new windows.
Notes
- Created by: Alan Coleman
- Web Site: http://www.alancoleman.co.uk
- Posted: June 11, 2007
Source Code
Paste this source code into the designated areas.
External file
Paste this code into an external JavaScript file named: targetAttribute.js
/* This script and many more are available free online at
The JavaScript Source!! http://javascriptsource.com
Created by: Alan Coleman | http://www.alancoleman.co.uk */
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”;
}
}
}
// Multiple onload function created by: Simon Willison
// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != ‘function’) {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
externalLinks();
});
Head
Paste this code into the HEAD
section of your HTML document.
<script type=”text/javascript” src=”targetAttribute.js”></script>
Body
Paste this code into the BODY
section of your HTML document.
<ul>
<li><a href=”http://www.webdeveloper.com/” rel=”external”>Web Developer</a></li>
<li><a href=”http://javascriptsource.com/” rel=”external”>JavaScript Source</a></li>
<li><a href=”http://www.webreference.com/” rel=”external”>WebReference.com</a></li>
</ul>