ScioSoft's Community Blogs Optimized IT musings for the technically inclined

Open external links in a new window: Add target="_blank" using jQuery

by James Fielding 5. February 2011 13:32

When it comes to site optimization, there's always lots to do. Richard Florance has a great post on making ASP.NET sites run more efficiently. One thing that Richard doesn't talk about is on the client-side, specifically using jQuery (or JavaScript) to add repetitive, non-critical, page elements and attributes. Here's a quick tip that you can use to reduce a page's size: Add target="_blank" to <a> tags using jQuery.

$("a").filter(function () {
        return this.hostname && this.hostname !== location.hostname;
    }).each(function () {
        $(this).attr({
            target: "_blank",
            title: "Visit " + this.href + " (click to open in a new window)"
        });
    });

The above code filters all the hyperlink tags by hostname, and then adds a target="_blank" as well as a title attribute to each external link. If you don't like the title attribute, change or remove it. You could also take this one step further and add a css class or image/styling directly to each external link to identify them as external (although you could accomplish this using straight css, too); I'll leave this to you. More...

Sciosoft Systems is a Canadian web design & development company based in Muskoka, which is in central Ontario. We provide ASP.NET website & Windows Server application development services to small and medium-sized business, as well as local government and not-for-profit groups. If you have a website project you’d like to discuss, please visit us at www.sciosoft.com.

Share |

Tags: , , ,

jQuery | Web Design

RecentComments

Comment RSS

The opinions expressed herein are the personal opinions of the contributors and do not necessarily represent the views of Sciosoft Systems Inc.