jQuery: 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:
- Target links to _top with jQuery (Wednesday, July 21st 2010)
- Iterate through an associative array the jQuery way (Friday, January 29th 2010)
- Add an offsite link icon after external links with jQuery (Saturday, March 28th 2009)
- Use jQuery to make all offsite links open in a new window (Tuesday, March 24th 2009)
- jQuery's document ready initialization (Friday, February 20th 2009)

Comments
blog comments powered by Disqus