Thursday, February 19, 2009

Adding jQuery tooltips to Wicket pages

Tooltips are little popup windows that appear on mouse over and are one handy way to provide context-sensitive help to users. It's easy to add tooltips to form fields (or any other tags, really) using jQuery and Wicket. See the screenshot for an example.

Here's how to add tooltips to your Wicket forms. I'm using the label tag to associate the text next to the field with its field, and assigning the tooltip to the label field also. This means that the user will see the tooltip whether they mouse over the label or the field. The first example is the simplest, where I provide a string for the tooltip directly in the code. The second example uses Wicket's powerful model capability, which means you can get the tooltip string from a properties file, a bean property, even a database.

There are many jQuery plugins that can display tooltips. I'm using this one., which I found easy to use and very well-behaved on various browsers. There are lots of options for styling, but I'm using the default style.

I'm using version 1.4-rc2 of Wicket, version 1.2.6 of jQuery, and version 1.3 of the jQuery Tooltip plugin. I put the .js files in the folder src/main/webapp/js of my maven project, and the .css file in the folder src/main/webapp/css of my maven project.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

<html xmlns="">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.tooltip.js"></script>
<script type="text/javascript">
$(function() {
<link rel="stylesheet" href="css/jquery.tooltip.css" />

<form action="" wicket:id="myform">
<label for="one" wicket:id="">My text field 1:</label>
<input id="one" wicket:id="" type="text"/>
<label for="two" wicket:id="label.two">My text field 2:</label>
<input id="two" wicket:id="text.two" type="text"/>

public class Tooltips extends WebPage {

public Tooltips() {

Form<String> form = new Form<String>("myform");

SimpleAttributeModifier am1 = new SimpleAttributeModifier("title", "hi tooltip 1");
AttributeAppender tt = new AttributeAppender("class", new Model<String>("tooltip"), " ");
Label label1 = new Label("", new Model<String>("My Form Field Label 1:"));
TextField<String> textField1 = new TextField<String>("");

AttributeModifier am2 = new AttributeModifier("title", true, new Model<String>("hi tooltip 2"));
Label label2 = new Label("label.two", new Model<String>("My Form Field Label 2:"));
TextField<String> textField2 = new TextField<String>("text.two");


1 comment:

Alexander Lipatov said...

Useful post bro! Adding tooltips to whole project is a pain...