jQuery Tip: Open links in new windows with valid (X)HTML Strict DocType

Update: forgot the return false (without it, the page would open in a new window and replace the current page).

In (X)HTML Strict, anchor tags linking to other pages are not allowed to have the target attribute. Because of this, links can not be opened in a new window if the page validates. However, with jQuery and the addition of a class to anchors that open in new windows: <a href="http://jquery.com" class="external">jQuery</a> you can do this in just one line of code: $("a.external").click(function(){window.open(this.href);return false;});. If you add any more links dynamically (i.e. through AJAX), you would have to run this again, but preferably not anonymously (i.e. inline function).

function openWindow()
{
    window.open(this.href);
    return false;
}
// shorthand for $(document).ready(function(){...})
$(
    function()
    {
        $("a.external").click(openWindow);
    }
)

Comments

Popular posts from this blog

Select box manipulation with jQuery

Basic Excel Spreadsheet Generation (ASP/ASP.NET)

Link: HTML Agility Pack (.NET)