The blog

Add some pretty form element help text with the jQuery Tooltip Plugin

Here’s a quick tutorial going over how to get a simple tooltip working using the jQuery library and the Tooltip plugin. We’ll set up the help text to be displayed when a user mouses-over a question mark next to a form element.

View a demo.

First, let’s start with a simple form:

<form>
    <p><label for="name">your name</label><a class="tooltip" title="Please enter your first and last name">?</a></p>
    <p><label for="email">your email</label><a class="tooltip" title="Please enter your valid email address">?</a></p>
    <p><label for="phone">your phone</label><a class="tooltip" title="Please enter your telephone number">?</a></p>
    <p><label for="url">your website/url</label><a class="tooltip" title="Please enter your home page or other website address">?</a></p>
    <p></p>
</form>

Notice that each “?” has is wrapped in an anchor <a> with a class of tooltip. The value for the title attribute will be displayed as the help text for the tooltip.

Next we’ll add some CSS to make it codetty.

body {
  font: normal 100% Georgia, serif;
  color: #333;
}
form {
  margin: 1em; padding: 1.2em;
  border: solid 1px #333;
  background: #eee;
}
form p {
  margin: 0; padding: 0.6em 0;
  clear: both;
}
form label {
  width: 10em;
  float: left;
}
form input.text {
  float: left;
}
form a.tooltip {
  cursor: pointer;
  padding: 0 0.4em;
  background: #333;
  color: #fff;
}

And here’s our form so far:

Our form

Our form

Now let’s add in a bit of CSS specifically for the tooltip itself:

#tooltip {
    position: absolute;
    z-index: 3000;
    background: #930;
    border: solid 1px #333;
    color: #fff;
    padding: 0.8em;
    font-weight: normal;
    font-size: xx-small;
}

And finally we gotta get it kicking when the dom is ready:

$(document).ready(function(){
  $('a').tooltip();
});

That’s it. Hope it helps!

Leave a Reply