Target links to _top with jQueryTarget links to _top with jQuery

Posted July 21st, 2010 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 like so:

if(top.location != location) {
  top.location.href = document.location.href;
}

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').each(function() {
            if(!this.target) {
                this.target = '_top';
            }
        });
        $('form').each(function() {
            if(!this.target) {
                this.target = '_top';
            }
        });
    }
});

Related posts:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus