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’

3 comments:

  1. Boy thatees cool - how do you get these ideas

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

    ReplyDelete
  3. 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/

    ReplyDelete