XHTML compliant Javascript to open links in a new window

January 08 2008

To be XHTML strict you cannot use the target attribute in anchors. This means you cannot use target="_blank” to open a link in a new window. Sometimes this is the desired behavior, you simply do not want people to navigate away from your site, yet you want them to be able to view a resource you have linked to. My solution, which I think I grabbed from a javascript book I got a while back, works by taking advantage of your clean XHTML. All you need to do is add a class called “popup” to your anchor and you are ready to roll.

We want our javascript function to run only after the page has been loaded. This is a small function that will allow you to stack multiple functions into the window.onload method. This will make it easy to add additional functionality later on if we need it. You can only assign one function to the onload method as additional assignments will overwrite the previously defined function. We are going to use a function called addLoadEvent to make adding multiple functions to the onload method easier.

function addLoadEvent(func) {
  
var oldonload = window.onload;
  if (
typeof window.onload != 'function') {
    window
.onload = func;
  
} else {
    window
.onload = function() {
      oldonload
();
      
func();
    
}
  }
}

Now we create our popup function. This function will scan the DOM for anchor tags, then loop through each one looking for those with a class of “popup”. The ones that do are then assigned on onclick event handler that calls a function which will open the link in a new window when clicked.

function preparePopups() {
  
if (!document.getElementsByTagName) return false;
  var
lnks = document.getElementsByTagName("a");
  for (var
i=0; i<lnks.length; i++) {
        
if(lnks[i].className.indexOf("popup") != -1){
      lnks[i]
.onclick = function() {
        popUp
(this.getAttribute("href"));
        return
false;
      
}
    }
  }
}

Now we can write the popUp function that is called from the onclick event handler.

function popUp(winURL) {
  window
.open(winURL);
}

Last, but not least, we pass our preparePopups function to addLoadEvent so that it is run once the document is fully loaded.

addLoadEvent(preparePopups);

Comments

Leave a Comment

Allowed / Requried

Only these elements are allowed in submitted comments:

  • <a href="http://www.mysite.com/">my site</a>
  • <img src="http://www.mysite.com/myimage" alt="image" />
  • <blockquote>quote</blockquote>
  • <em>my emphasized text</em>
  • <strong>my bold text</strong>
  • <code>my code</code>

* = Required fields

Commenting is not available in this section entry.