Sergio Panagia Blog

Advanced Placeholder with Javascript: hide on first key pressed

MooTools Quick DemojQuery Quick Demo

Common design patterns about Placeholder hide labels on focus event, so when user select the input box.

Another technique hides the label after user’s focus, precisely it does on first letter typed (it’s the case of new twitter welcome-page).

First, let’s create the placeholder element by finding input box position in absolute terms, considering we have an input element with id = “name”

jQuery JS

//grab input element
var field = jQuery('name');
//now create a new element to serve as placeholder
var cover = jQuery('
name
'); jQuery('#wrap').add(cover).appendTo(document.body); cover.css({ 'position':'absolute', 'top': field.offset().top, 'left': field.offset().left, 'padding-left': field.css('padding-left'), 'padding-right': field.css('padding-right'), 'padding-top': field.css('padding-top'), 'padding-bottom': field.css('padding-bottom'), 'font-size': field.css('font-size') });

So now we created the placeholder and placed over the input box by copying some style attributues, remember to update this element position on window resize:

jQuery(window).resize(function()
{
	cover.css({
	'top': field.offset().top,
	'left': field.offset().left
	});
});

And now let’s manage the other events:

//placeholder covers the input box,
//so if the user clicks it, give focus to the element below
cover.click(function()
{
	field.focus();
});

On user’s first key press, apply a nice effect on placeholder text:

field.keydown(function()
{
	if(!this.value.length)
	{
		cover.animate({fontSize: "0"},100);	
	}
});

On input box blur (when user escapes from input-box), restore placeholder:

field.blur(function()
{
	if(!this.value.length)
	{
		cover.animate({fontSize: "3em"},300);
		field.value = "";	
	}
});

I included a MooTools version too, below.
Just remember you can add your desired effects on field.focus() function (css transitions etc).

MooTools DemojQuery Demo

 

One Response to Advanced Placeholder with Javascript: hide on first key pressed

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *

*

*

È possibile utilizzare questi tag ed attributi XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>