XHTML: Open a link in a new window

Mario Laflamme March 9th, 2006

Sure, you can to use the tag target=”_blank” to open a link in a new window with XHTML, but this tag is not valid. A simple and effective alternative is to insert the following JavaScript function in your pages and to add the tag rel=”external” to the appropriate links.

<script type=”text/javascript” language=”JavaScript”>
    function externalLinks() {
        if (!document.getElementsByTagName) {
            return;
        }
        var anchors = document.getElementsByTagName(”a”);
        for (var i=0; i<anchors.length; i++) {
            var anchor = anchors[i];
            if (anchor.getAttribute(”href”) &&
                anchor.getAttribute(”rel”) == ”external”) {
                anchor.target = ”_blank”;
            }
        }
    }
    window.onload = externalLinks;
</script>

Entry Filed under: JavaScript, XHTML

1 Comment

  • mike3 September 30th, 2006 at 1:58 am

    thanks for posting this! i had been trying to get my pages to pass the w3c xhtml validator but still have some links open in separate windows.

Leave a Comment

Required

Required, hidden

Some HTML allowed

Trackback this post  |  Subscribe to the comments via RSS Feed

Schedule

March 2006
M T W T F S S
    Apr »
 12345
6789101112
13141516171819
20212223242526
2728293031