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’



Will you give this article a +1 ? Thanks in advance


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

5 comments:

Goff said...

Boy thatees cool - how do you get these ideas

Baba said...

Wow, this is something new for me. That's really cool. I will try it for my blog. This code can be used not for blogspot right? Since my blog isn't in blogspot. - Give your opinion about jijiji by fill a survey at http://www.keyr.com/analysis/jijiji.html

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.

Michael 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/

Leslie Lim said...

I just wanna say thank you for sharing the content and wish you all the best for your website and your whole team.

Shella
www.imarksweb.org