Tooltips on forms using jQuery

Just recently someone posed the question to me, “How would I use a span as a Tooltip when someone hovers an input?” I was feeling particularly helpful so I decided to take a few minutes to come up with a solution. Whilst its a simple bit of script, as any developer knows, its sometimes the most simple things that people don’t document!

I’m going to be using jQuery to do this, so obviously a bit of knowledge about this library will be useful if you want to completely understand the code, if not, copy, paste and enjoy!


<label for="firstName">First Name<span>Please enter your first name</span></label><input id="firstName" class="tooltip" name="firstName" type="text">
<label for="surname">Surname</label><input id="surname" name="surname" type="text">


label { width: 270px; float: left; display: block; padding-left: 5px; }
label span { padding-left: 10px; }
input { float: left; }

As you can see I’ve made an extremely simple form styled crudely that does nothing. This isnt a tutorial on HTML though so hopefully that can be excused. What we are aiming to do is to display the content of the span tag next to the label when we hover any input with the class tooltip.

The Javascript

$(window).load(function() {
	// hide any spans that are children of a label
	$('label span').hide();
	// attach a function to the hover event on an input with the class tooltip
	$('input.tooltip').hover(function(e) {
		// define a var called inputName as the name attribute of the events target
		inputName = $('name');
		// select the child span of the label that has a for value that matches the inputName var and show it
	}, function(e) {
		// using the call back function of the hover event select the child span of the label that has a for value that matches the inputName var and hide it

Thats all there is to it! Obviously this can be done in many ways but I thought I’d share this solution. You can see an example of this working here