thedigitalfeed.co.uk content
thedigitalfeed.co.uk/Code
Javascript, XHTML and External Links
Posted on Wednesday the 6th of December, 2006
www.thedigitalfeed.co.uk/code/2006/12/06/javascript-xhtml-and-external-links
We know that the
This is a very simple little Javascript. It loops through all of the <a> tags in the document. For each one, it checks the
For each external link, the Javascript adds an attribute of
target attribute is not part of the XHTML 1.0 spec. So how do we validate XHTML code, retain accessibility, and still have our external links open in a new window? Javascript, of course!This is a very simple little Javascript. It loops through all of the <a> tags in the document. For each one, it checks the
href attribute against the current URL, read using window.location(). If the href does not match, it decides it is an external link.For each external link, the Javascript adds an attribute of
target="_blank". In this particular example, it also appends a class of 'ext' for CSS if you want to add an icon. Finally, it appends text to an existing title tag, or creates one if it doesn't exist.
var _a = document.body.getElementsByTagName('a');
var _u = window.location.href.split('?')[0];
for(var i=0;i<_a.length;i++){
if(_a[i].href.indexOf(_u)==-1
&& _a[i].href.indexOf('http:')>-1
&& _a[i].href.length>0){
_a[i].setAttribute('target','_blank');
_a[i].className = _a[i].className+' ext';
if(_a[i].title.length>0){
_a[i].title+= ' (Opens in a new window)';
}else{
_a[i].title = '(This link opens in a new window)';
}
}
}