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

Posted 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:


Comments