Adding the Anchor Text as a Tooltip using jQuery

The title attribute is an easy way to add tooltips to your HTML anchors. I recently had a situation where I had to add a tooltip to every HTML anchor. I did this using jQuery and it was quite simple. Here’s the code:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Adding The Anchor Text As The Title</title>
<
script language="javascript" type="text/javascript"
src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<
script type="text/javascript" language="javascript">
$(document).ready(function() {
$('a').each(function() {
$(this).attr("title", $(this).text());
});
});
</script>
</
head>
<
body>
<
a href="http://www.google.com">Google Website</a><br />
<
a href="http://www.yahoo.com">Yahoo Website</a><br />
<
a href="http://www.bing.com">Bing Website</a><br />
</
body>
</
html>

The code above will add a tooltip to each HTML anchor. The tooltip will be the text displayed in the browser for each anchor. Here’s the result:

image

Note: In the image above, the tooltip shows ‘Google Website’ when the user hovers over the first link i.e ‘Google Website’






About The Author

Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET and regular presenter at conferences and user groups throughout Australia. Being an ASP.NET Insider, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with JavaScript. He also blogs regularly at DotNetCurry.com. Follow him on twitter @malcolmsheridan

3 comments:

Goff said...

Boy thatees cool - how do you get these ideas

Malcolm Sheridan said...

@Miguel
You can have this in any page so that all your anchors will have a tooltip. Have it in the page load event.

combs1945 said...

I found a great page that give numerous downloadable examples of how to change the text inside an anchor using jQuery. They are really helpful for web 2.0 and web 3.0 sites.

http://www.ajaxera.com/jquery-change-text-in-anchor/