Monday, January 30th, 2006

How to make external links exit HTML frames?

Filed under: — Daniel Lemire @ 13:33

Generally, avoiding copy and paste is a great idea whether you are designing a web page or sending people on the moon.

A common problem with the badly constructed web sites relying on HTML frames is that external links are loaded within the frame which poses serious usability issues. A better solution is not to use frames, but sometimes, you are stuck with them. I had an argument recently with some people who insisted they had to add a “target=’_top’” attribute to all external links, in all pages.

Using the DOM API and JavaScript, you can easily add the correct target attribute to all external links without any copy and paste if you follow the convention that external links begin with “http”. Simply add the following within the “head” element of your web page:


<script type="text/javascript">
function externalLinks() {
var anchors = document.getElementsByTagName("a");
for(var i=0; i<anchors.length; i++) {
var anchor = anchors[i];
var myurl = anchor.getAttribute(”href”);
if( ! myurl) continue;
if(myurl.indexOf(”http”) == 0) {
anchor.setAttribute(”target”,”_top”);
}
}
}
window.onload = externalLinks;
</script>

Of course, this relies on JavaScript being enabled, you might have cross-browser issues, and it adds an overhead to the processing of the page.

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Warning: When entering a long comment, please ensure that you make copy of your text prior to submitting it. If the server should fail or if you hit a bug, you might lose your work. I am not responsible for your lost effort.

To spammers: I carefully review every single post and make sure that spam gets deleted. You are wasting your time if you are manually entering spam using this form. Read my terms of use to see what I consider to be abusive.

Example: I + II + IX= XII. Yes, you have to enter a roman numeral. (Answer must be in upper case.)

« Blog's main page

25 queries. 0.298 seconds. Valid XHTML

Powered by WordPress

Subscribe to this blog in a reader or by Email.