01590 700 125 - 02380 988 977 hello@bluebit.co.uk

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!

The HTML

<form>
<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">
</form>

The CSS

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 = $(e.target).attr('name');
		// select the child span of the label that has a for value that matches the inputName var and show it
		$('label[for='+inputName+']').children('span').show();
	}, 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
		$('label[for='+inputName+']').children('span').hide();
	});
});

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

Some parts of this site require the use of cookies for the site to function correctly. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close