Connect with me

jQuery Inline Form Labels

I’ve been seeing the trend of applying inline labels on form elements more and more these days. So I definitely needed to come up with a solid solution that would help me easily apply this effect.

Maybe I need to explain a little better what I am referring to. Instead of using a label that is next to or above the input element, the label is actually within the input. Then, when the input is focused, the label goes away and you can enter your value into it. Finally, when the input is no longer focused, if there is no value entered, the inline label is then added back in.

My Solution

The title attribute.

It’s so simple, but perfect. A great benefit of using the title attribute, is that when you hover over the input, you get a little tooltip displaying the inline label. So all I need to do is add a title attribute with the text that we want to have show up as the inline label. Then, we just use a little jQuery to make it all happen.

The jQuery

First, we want to select each input that has a title attribute, once the document is loaded:

After that, we want to setup a function that will fire once the input is focused. When it is focused, if the value is equal to the title attribute, we want to set the value to nothing and add a class of focused:

The reason why we add the class of focused is so that we can change the text color, border or anything to make it noticeable that the input is being focused. You can see this effect in the demo.

Finally, we want to add a function that will fire when the input loses focus. When it does, if the input value is empty, we want to set the value back to the title attribute and remove the class of focused: