jQuery Attach Focus and Blur Function

Todays code snippet uses jQuery to attach blur and focus listeners to an input element, so default text is shown (like "enter your username") and that text is cleared when the user focuses into the field.

Getting ready

Setup an input element somewhere on the page:

<input id="myInputId" type="input"/>

And setup the following CSS class to handle the focusing styles:

.unfocused {
	color: #999;
}

How to do it…

Here is the function:

function attach_focus_and_blur(elem, sText) {
	var elNode = $(elem);

	elNode.focus(function() {
		if (elNode.val().trim() == sText) {
			elNode.val("");
		}

		elNode.removeClass(unfocused);
	}).blur(function() {
		if (! elNode.val().trim()) {
			elNode.val(sText);
			elNode.addClass(unfocused);
		}
	});

	if (sText == elNode.val().trim()) {
		elNode.blur();
	}
	else {
		elNode.focus();
	}
}

To use the function:

attach_focus_and_blur(myInputId, default text);

How it works…

Pass an element id or jQuery element as the first argument of the attach_focus_and_blur() function and the default text as the second argument. The function will attach a focus handler that clears existing text if it is equal to the default text and removes the unfocused class. It also attaches a blur handler that restores the default text if nothing was entered and the unfocused class. The last part of the function fires the appropriate event handler depending on the initial state of the input.