jQuery Tooltips Made Easy
Inspired by a recent post on forrst.com (don't ask, I haven't got spare invites) I decided to write an easy to implement jQuery tooltip class for use with forms. A few points were raised in the comments of the original post, many of which I consider to be very relevant and have been taken into account when writing this code:
- Code to be as simple and minimal as possible.
- Tooltips to be semantically correct - this means they are NOT wrapped in label tags, but rather in spans
- Non javascript fallback to be in place (does anyone browse without it anymore?)
- Reliant on CSS for the basic styling (a personal favourite)
The form's HTML
Before getting carried away with css or javascript - I began with coding a basic html form:
<form> <label for="username">Username:</label> <input type="text" id="username" name="username" /> <span>Enter your username (4-12 characters)</span> <label for="userpass">Password:</label> <input type="text" id="userpass" name="userpass" /> <span>Enter your password (Letters and Numbers)</span> </form>
With the basics in place, I assigned a class of tooltip to each of the spans I wanted to target with the script (and also css).
<span class="tooltip">Enter your username (4-12 characters)</span>
Next came some basic styling of the form, nothing particularly special, but enough to showcase it:
form {
background-color: #f6f6f6;
margin: 10px;
padding: 10px 20px 20px;
border: 1px solid #e6e6e6;
font: 12px Arial, Helvetica, sans-serif;
width: 210px;
overflow: visible;
white-space: nowrap;
}
label {
font-size: 12px;
color: #666;
display: block;
padding-bottom: 2px;
padding-top: 10px;
}
input {
background: #fff;
border: 1px solid #d0d0d0;
font-size: 12px;
color: #933;
padding: 5px;
width: 200px;
}
.tooltip {
padding: 5px;
background: #666;
border: 1px solid #606060;
color: #ddd;
}
Now the fun begins... the javascript
First step is to hide all of the tooltips:
$(function() {
$('.tooltip').hide();
});
Pretty easy so far huh? If it's not working for you, make sure you've included jQuery before the script above.
The next step is to associate an event to display the relevant tooltip when an input gains focus, so our script now looks like this:
$(function() {
$('.tooltip').hide();
$('.tooltip').prev('input').focus(function(){
$(this).next().fadeIn('fast');
});
});
Take this a step further to hide the tooltips on loss of focus and we get:
$(function() {
$('.tooltip').hide();
$('.tooltip').prev('input').focus(function(){
$(this).next().fadeIn('fast');
}).focusout(function(){
$(this).next().fadeOut('fast');
});
});
So there you have it - simple, functional tooltips in a few lines.
Comments:
blog comments powered by Disqus