XHTML and “external-window” links

by Naneau

In the good old days of HTML 4, making a link open in a new window was as easy as putting target=”_blank” inside the a (or A) tag. Apparently, you can’t take yourself serious anymore if you still output HTML 4. XHTML really is the way to go.

XHTML strict doesn’t support the target attribute for links. I think the reason behind is that it is considered behavior, not structure. If you go down the XHTML road, you should write valid code, so you can’t use the target attribute anymore. Luckily, there’s a cute little language that you can use to specify behavior for your website: JavaScript.

With Prototype, doing this is a breeze. Using the rel attribute on links is fine, and we can use it to differentiate between ‘regular’ ones and the ones we want to open in a new window:

1
2
3
4
5
6
7
8
9
10
11
12
13
Event.observe(window, 'load', function(){
    //after the window finishes loading
   
    var anchors = $$('a');
    //all anchors
   
    anchors.each(function(anchor){
        if ((anchor.getAttribute("href")) && anchor.getAttribute("rel") == "external") {
            //if it has a href attribute and rel="external"
            anchor.target = "_blank";
        }
    });
});

By using the double $$ function, you can get all elements by a css rule. In this case, all the links (‘a’). If you would like to make all your links inside your weblog post (which could be inside a div with class “post”) external, you could write something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
Event.observe(window, 'load', function(){
    //after the window finishes loading
   
    var anchors = $$('div.post a');
    //all anchors inside div.post
   
    anchors.each(function(anchor){
        if ((anchor.getAttribute("href"))) {
            //just a check for a href now
            anchor.target = "_blank";
        }
    });
});