Target links to _top with jQuery

Posted in Javascript -

Amazingly some people still use <frameset> and <frame> tags around the web, as I discovered the other day when someone linked my Running Calendar website into their frameset website. A common approach to this problem is to detect if the page is in a frameset and to bust out of it; in this post I offer an alternative which is to change the target for all links to _top where a target is not already set.

Busting out of the frameset with Javascript

The common method is to bust out of framsets automatically is like so:

if(top != self) {
    top.location = location;

The downside with doing this is some (or all) of you page will load first and then the Javascript will run and it can look a little messy (although I suppose no worse than having your site looking as if it is part of another site).

Using jQuery to target all links and forms to _top

I decided to take a different approach and change all links to target _top instead where they don't already have a target set. This means there's no sudden page reload, and I don't have to go through all my code and templates and change <a> and <form> tags.

Add the following code to achieve this. It will only modify the target attribute if the page is contained in a frameset, and the target is not already set:

$(document).ready(function() {
    if(top.location != location) {
        $('a, form').each(function() {
            if(! {
       = '_top';

Or use <base> to target a default

Alternatively, you can use the <base> target to set a default target; all links with then use that target unless a different one is specified in the link itself. The target attribute was deprecated but the W3C undeprecated it with HTML5 and added it to the <base> element as well; see my use base target to target links instead of using Javascript post for more details.

Related posts: