External Popup Links Using jQuery

With the deprecation of the target attribute in XHTML Strict, opening links in new windows has become a bit trivial, if not annoying, to standardize. I always look for a consistent, unobtrusive approach that degrades gracefully; and since I use jQuery quite frequently, this is how I usually handle them.

The solution is a small piece of jQuery code in your $(document).ready() section:

$(document).ready( function() {
    $(document).on('click', 'A[rel="external"]', function(event) {
        event.preventDefault();
        window.open( $(this).attr('href') );
    });
});

Now, add rel="external" to all of the links that you want to open in a new window:

<a href="http://domain.com/" rel="external">Domain.com</a>

From here on out, users that have JavaScript enabled will receive external pages in new windows, while those without JavaScript will still be directed to the appropriate location.

I use rel="external" because it's generally a good practice to limit popup links to external websites only. You could very well use rel="popup" instead, but I prefer the former for semantics.

Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.