I’ve always seen it done. Clearing the input field on focus.

JQuery seems to be pretty simple. Its just the syntax you have to get used to.

First the html markup

Sign up

Notice that for each input field I have an id, name, and alt attribute

Next integrating JQuery

Notice that I’m using googleapis to host the javascript. It seems that this is a better/faster alternative to hosting it directly on your host, plus google servers are most likely cached and will provide a better experience for the client.

Next building the JQuery plugin

		$.fn.clearSetFocus = function(iAttr)

We’re gonna create a namespace for ourselves. In my case, I named my function clearSetFocus. The $ creates a new JQuery object. you could also use jQuery(). So, I’ve created a new function named clearSetFocus and I’m taking in one parameter, called iAttr.

To actually attach this plugin to an element all I have to do is to call it.

Calling the plugin


Notice that I call the document.ready function before I add my plugin to the elements. I’ve found that if I don’t do that then the js could execute before the elements are loaded and make the script fail. So what I’ve done is create a new jQuery object for the element #newsName and attached the plugin clearSetFocus with the parameter alt.

Back to writing the plugin.

The plugin

//name my function clearSetFocus
		$.fn.clearSetFocus = function(iAttr)
			//on focus
				if ($(this).val() == $(this).attr(iAttr))
			//on blur - chained functionality	
				//get the value currently in the input
					//replace the value with the alt value

The this refers to my element that I’ve attached the plugin to. so in this case the element #newsName. I attach the function focus() – which allows me to add a function to when the user focus’ on the element. In this case, my logic is simply, if my value is the same as my alt value, then clear it. on blur() – which means to navigate away from the element, my logic is if the value’s length is 0, but the alt value back in.

Couple things to note.
.val() – this allows me to either get the value associated with the element
.val(“test”) – allows me to set the value of the element
.attr(“id”) – allows me to retrieve the value of the attribute of the element. so if the markup was

, I would get test

All done!