jQuery: set title of anchor tags to the href for offsite linksjQuery: set title of anchor tags to the href for offsite links

Posted July 6th, 2010 in Javascript

Over a year ago I posted how to use jQuery to make all offsite links open in a new window. I recently received a comment on that page asking how to make the title attribute of all anchor tags on a page for offsite links be the same as the href. This post shows how to do this with jQuery, but also leaves any <a> tags with a title as-is.

Set the title tag to the href for all external links

Obviously you need to have the jQuery library included and then add the following piece of code into the HTML or your main Javascript file:

$(document).ready(function() {

    $('a').each(function() {
        if( this.hostname && this.hostname != location.hostname && !this.title ) {
            this.title = this.href;
        }
    });
   
});

That's all there is to it. Now after the page has loaded, all external links with have their title set to the same as the href for any that don't already have it set.

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