xHTML strict and opening a url in a new window

If you need to validate your web pages against the xHTML Strict DTD, you will run into some practical problems. One of these problems is that according to this DTD, the target attribute for a-elements is deprecated. So how then does one create links that will open a web page in a new window?

The solution is found in a combination of Javascript and CSS. Basically it’s quite simple: we provide every link that needs to be opened in a new window with a class. Then we use Javascript to track down all these links and assign the appropriate behaviour. Let’s see how this works.

The CSS part

We apply a separate class to all links to be opened in a new window. We may call this class something like ‘newwin’, so we get some indication on its purpose. If needed we may add some visual styling tothis class, but the principal purpose of the class is to identify these links so we can add some onclick behaviour.

<a href="http://www.somewebsite.com" class="newwin">Some website</a>

The Javascript part

We include a function in the head of the document that makes it possible to open a url in a new window.

<script type="text/javascript" src="openstrict.js"></script>

We see the following when we look at the file ’openstrict.js’.

function looplinks(){
   var links = document.getElementsByTagName("a");
   if(links){
      for (var i = 0; i < links.length ;i++){
         if(links[i].className == "newwin"){
            links[i].onclick = openstrict;
         }
      }
   }
}
function openstrict(){
   window.open(this);
   return false;
}

The function ’looplinks()’ is called at the end of the xHTML document. This function looks up all links in the document and checks whether a link has a class ‘newwin’ added to it. If so, an onclick event is defined for the link. In this onclick event, the function  ‘openstrict()’ is called.

The function ’openstrict()’ catches the clicked element and uses the value of its href attribute to open this url in a new window, using the Javascript method window.open. We add the ‘return false’ statement to prevent opening the url in the current window.

The last thing left to do, is calling  ‘looplinks()’. We do this by placing the following just before the closing body tag.

<script type="text/javascript">looplinks();</script>

That’s it. No rocket science, valid xHTML Strict and an easy way to open links in a new window. Tested under Windows  in IE6, IE7, Firefox 2 en 3 and Safari 3.1.

  • Trackback are closed
  • Comments (0)
  1. No comments yet.

You must be logged in to post a comment.