Wednesday, August 5, 2009

Tooltips for Links

Today's tinkertoy explores how jQuery can provide enhanced interface experiences with very little code. It adds a popup tooltip to every link (<a> tag) on the page.
Now, there are plenty of jQuery plugins for doing tooltips. Please don't think my little effort is presented as a production-ready alternative to them; it's not. It's just a way to get you thinking about how jQuery can do very cool stuff for your users without causing you to write a ton of code.
That said, here's a screen shot of today's experiment in action:

Here's the code, as HTML, JavaScript, and CSS. Tomorrow we'll step through it.

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript" src="/jquery/jquery.dropshadow.js"></script>
<script type="text/javascript" src="jqTooltips.js"></script>
<link type="text/css" rel="stylesheet" href="jqTooltips.css">
</head>
<body>
<h1>jQuery Tooltips for Links</h1>
<p>This page shows how some simple jQuery code can set up popup tool tips for links. The premise is that this page will be used by web neophytes who might need some help to understand how everything works. So let's have a few links:

<ul>
<li><a id="lnkProtonArts" href="http://www.protonarts.com">Proton Arts</a></li>
<li><a id="lnkThejQueryWebsite" href="http://www.jquery.com">The jQuery Website</a></li>
</ul>

<p>Of course, if we just insert a stealthier link to <a href="http://www.youtube.com">YouTube</a> within some paragraph text, jQuery picks up on that one, too.</p>
</body>
</html>

JavaScript:


function makeATooltip(atag){
tipTop = atag.offset().top - 20;
tipTop += "px";
tipLeft = atag.offset().left + 30;
tipLeft += "px";
tipText = "Click on this link to visit " + atag.text() + ".";
tipWidth = tipText.length * 7 + "px";
tipHTML = "<div class='tooltip' id='";
tipHTML += atag.attr("id");
tipHTML += "Tip' ";
tipHTML += "style='{position: absolute;; ";
tipHTML += "top: " + tipTop + ";; ";
tipHTML += "left: " + tipLeft + ";; ";
tipHTML += "width: " + tipWidth;
tipHTML += "}'>"
tipHTML += tipText
tipHTML += "</div>"
atag.after(tipHTML);
$("#" + atag.attr("id") + "Tip").dropShadow();
}

function destroyTooltip(linkID){
$("#" + linkID + "Tip").removeShadow().remove();
}

$(document).ready(function(){
$("a").hover(function(){
makeATooltip($(this));
}, function(){
destroyTooltip($(this).attr("id"));
});
})


CSS:

body{
font-family: Verdana, Helvetica, sans-serif;
}

.tooltip{
padding: 5px 0px 0px 5px;
background-color: yellow;
height: 25px;
font-family: Verdana, Helvetica, sans-serif;
font-size: 75%;
font-weight: bold;
text-align: center;
border: 1px solid black;
}

See you tomorrow!

No comments: