Changing Form Input Styles on Focus with jQuery
A lot of forms can be boring and plain, don’t let yours blend in. This tutorial will show you how to spice them up with CSS classes and default values that change according to which form item is selected. All with just a splash of jQuery.
The Goal
We want to make a form with input fields that change their appearance when they are focused on. Get on board and check out the example.
Step 1 – The Groundwork
First we’ll need to set up the form we will be using.
<form> <input name="status" id="status" value="Type something here" type="text"/> <input value="Submit" type="submit"/> </form>
I have included “Type something here” as the default value for the input. This is the text that will display initially but disappear when the field gets focus.
Step 2 – The CSS
Now we make the fields look pretty. I’ve done some styling based on my taste, but you will need to include classes for the active/inactive styles of the fields, I have used idleField and focusField.
<style type="text/css">
*{
margin:0;
padding:0;
font:bold 12px "Lucida Grande", Arial, sans-serif;
}
body {
padding: 10px;
}
#status{
width:50%;
padding:10px;
outline:none;
height:36px;
}
.focusField{
border:solid 2px #73A6FF;
background:#EFF5FF;
color:#000;
}
.idleField{
background:#EEE;
color: #6F6F6F;
border: solid 2px #DFDFDF;
}
</style>It is also important to note that if you want to remove the blue glow that Safari applies around the field in focus, you will need to include outline:none on those inputs.
Step 3 – Bring on the jQuery
Here’s the part where we add the on focus effects to the inputs in the form. We want a two things to happen when a input field gets focus, 1. The selected field will shift from the inactive class to the active one and 2. The default text inside the box (‘Type something here”) will disappear. Similarly, we want the opposite to happen when the field loses focus.
$(document).ready(function() {
$('input[type="text"]').addClass("idleField");
$('input[type="text"]').focus(function() {
$(this).removeClass("idleField").addClass("focusField");
if (this.value == this.defaultValue){
this.value = '';
}
if(this.value != this.defaultValue){
this.select();
}
});
$('input[type="text"]').blur(function() {
$(this).removeClass("focusField").addClass("idleField");
if ($.trim(this.value == '')){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});
});Let’s break down what we just put together, initiated by the page loading:
For every text input apply the class idleField to it
$('input[type="text"]').addClass("idleField");When a text input gets focus, remove the inactive style and add the active style.
$('input[type="text"]').focus(function() {
$(this).removeClass("idleField").addClass("focusField");
});When the user clicks the input field we want the text “Type something here” to go away, if the user has not already typed something else in. The following checks to see if the text value is what it started as when the form loaded. If it is, it gets cleared to make room for user input.
if (this.value == this.defaultValue){
this.value = '';
}If the user has already typed something in a field, instead of getting cleared when they click on that field again, we want the content to be highlighted.
if(this.value != this.defaultValue){
this.select();
}The next part of the script handles what happens when an input field loses focus, essentially doing the opposite of what was just explained.
$('input[type="text"]').blur(function() {
$(this).removeClass("focusField").addClass("idleField");
if ($.trim(this.value) == ''){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});One difference worth noting is the use of $.trim(), which cleans out white space leading and following user input. Keep in mind that if a user submits the form without altering the default values(“Type something here”), those are the items processed by the form. You can correct this by adding a check/action when the submit button is pressed.
The Finished Product
That’s pretty much the deal, now go forth and make some jazzy forms.















Discussion
January 25th, 2009 at 2:42 AM
I learned something today. Thanks.
But I didn’t get one thing.
if ($.trim(this.value) == ”){
this.value = (this.defaultValue ? this.defaultValue : ”);
Can you explain a bit more what is happening here?
I am looking forward to reading more.
January 25th, 2009 at 3:25 AM
no ofence but why write all the extra jquery when you can add input[type="text"]:focus in the CSS and it will work like a charm. (only on modern browsers, but that’s a small price to pay for the people that still use IE6)
January 25th, 2009 at 11:13 AM
@shinokada
$.trim(this.value) == ” strips away spacing before and after the value, which prevents them submitting a blank value by just hitting the spacebar.
this.value = (this.defaultValue ? this.defaultValue : ”); is a shorthand IF statement. This basically sets the current value of the field, to either this.defaultValue OR ‘ ‘ (More on that here – http://davidwalsh.name/php-shorthand-if-else-ternary-operators)
@Razvan
The one problem with doing this in CSS, besides IE6 users (sigh), is that you will lose the ability to have the text in box that disappears on focus. Although to be fair if you really wanted I’m sure you could emulate the effect by setting the background-image to text on inactive. But still, IE6 isn’t dead yet, we have to put up with them a little longer
January 25th, 2009 at 4:49 PM
Hi!
I wrote some similar code and shared it as well, perhaps you’d be interested in checking out my script:
http://claytonrabenda.com/web-development/css-stylizing-text-input-elements-with-background-images
January 25th, 2009 at 5:25 PM
I honestly don’t get this… So I’m pretty sure we can do this all with CSS (changing the border and background on focus), and the only thing this really does is add the ability to take text and make it disappear. But isn’t that already built in?
January 25th, 2009 at 5:26 PM
input type=”text” value=”Enter your email” onFocus=”this.value=””
(without angle brackets)
January 25th, 2009 at 5:39 PM
@Roux
As I said above, the :focus will cause errors in IE6, which prevents style changes for those people.
Furthermore with the way you have done it, it will not replace the text to “Enter your Email” when it loses focus.
January 25th, 2009 at 6:44 PM
Nice article, thanks! One thing, you need to add outline:none for Chrome as well.
January 26th, 2009 at 7:15 AM
Nice article.
You probably could try to chain the jQuery methods in order to save a little extra work (jQuery walk though the DOM 3 times in your example).
$(‘input[type="text"]‘).addClass( … ).focus( … ).blur( … );
January 26th, 2009 at 8:07 AM
I’ve just found your article and something bother me.
Where did you define the value of defaultValue (this.defaultValue) ?
January 26th, 2009 at 8:49 AM
@cx42net
defaultValue is already part of the DOM, so it’s all taken care of going in
January 26th, 2009 at 2:05 PM
Interesting write up. Great trick if you must support IE6 with this type of styling. Not sure it’s worth it (ROI) for the most part. I personally would rather use the css input:focus method. That’s a lot of code to support one browser. All that aside, I think this is a great trick to add to the toolbox.
January 28th, 2009 at 7:20 AM
Thanks Sam Dunn;
I am was really searching for this type of script so I got it by your help, but one thing I noticed that when I type the text in input and click outside of the input turn the new typed text to gray as it was with default text.
If there is any solution please suggest me.
Thanks & waiting for your reply.
January 28th, 2009 at 10:33 AM
@M. khalid
It’s good that you pointed that out, as I was debating whether or not to include it in the tutorial.
Basically it’s an easy fix. What you’ll want to do is come up with another class for the completed form input and adjust the code like this:
$(‘input[type="text"]‘).blur(function() {
if ($.trim(this.value == ”)){
$(this).removeClass(“focusField”).addClass(“idleField”);
this.value = (this.defaultValue ? this.defaultValue : ”);
} else {
$(this).removeClass(“focusField”).addClass(“completedField”);
}
});
January 28th, 2009 at 11:27 AM
I would argue that it’s not good practice to (ab)use the input value to do the job that the label element should be doing. – Have a look at the login form on my site – I’ve used jQuery to position the label elements over the top of the inputs and hide/show them as necessary. This has semantic and accessibility benefits, and also allows for a non-javascript fallback by placing the labels next to the inputs.
James
February 6th, 2009 at 1:41 PM
Thank you posting this! I’ve been trying to figure out how do this with jQuery, but you nailed it!
February 17th, 2009 at 7:49 AM
Thanks for code
But I found a little bug there on these lines:
1. if ($.trim(this.value == ”)){
2. this.value = (this.defaultValue ? this.defaultValue : ”);
3. }
Notice, that right bracket should be after this.value in first line.. If is not, the condition never returns true.
This is my correct version:
if ($.trim(this.value) == ”){
this.value = (this.defaultValue ? this.defaultValue : ”);
}
But great work however!
February 26th, 2009 at 7:11 PM
@april > Thank you so much! Being somewhat new to javascript and using this tut to get used to the semantics, I was tearing my hair out trying to figure out where I messed up and why it wasn’t working!
Great tut by the way!
March 1st, 2009 at 11:57 AM
With a lot less code, you can do the following:
March 6th, 2009 at 3:33 AM
Very bad from accessibility point of view. You should use label and hide it then with JQuery.
Something like http://www.456bereastreet.com/archive/200710/autopopulating_text_input_fields_with_javascript/
April 5th, 2009 at 2:36 PM
How can I do same effect for Checkbox ?
Thanks
April 13th, 2009 at 2:47 PM
Hi ! Thanks all for this work……
Web Design Nepal Team
June 1st, 2009 at 12:27 AM
I think I got some result. Thank you here.
wpdigger’s last blog post..Theme Membership Sites – Are those really useful
June 11th, 2009 at 6:54 PM
Awesome example and explanation! In a situation where there’s multiple fields, how can we auto focus the very first input? I was hoping its as easy as implementing the
$(”:text:visible:enabled:first”).focus();method, seems to do the trick, but the auto focus won’t trigger addClass event. Perhaps I need to read up on event delegation?[rq=3813,0,blog][/rq]FLOverload iPhone Game
June 30th, 2009 at 11:05 PM
Good article, i wonder how to change this script to apply all others form field, like textarea, checkbox, radio, and etc.
Thanks.
July 30th, 2009 at 10:31 AM
wow!!! thanks
anyways, I agree with jack.
.-= torka´s last blog ..Traume =-.
August 6th, 2009 at 2:56 PM
@Noe Ruiz
I duplicated the .addclass, .focus and .blur lines and replaced ‘input[type="text"]‘ with ‘textarea’ for example.
I’m sure there’s an easier option than this as I am by far no expert.
August 6th, 2009 at 2:58 PM
Correction ( not @Noe Ruiz)
@jack
I duplicated the .addclass, .focus and .blur lines and replaced ‘input[type="text"]‘ with ‘textarea’ for example.
I’m sure there’s an easier option than this as I am by far no expert.
August 7th, 2009 at 10:08 AM
Thank you for this wonderful script
@brandon
Just replace input[type="text"] with input[type="text"],textarea and it will work fine, without writing useless code.
October 13th, 2009 at 10:56 PM
congratulations from chile,
works fine, but i modified the class “idleField”, in the background-color and instead of that i put an image (an icon) and looks very good.
but i have problems when i delete the text and then blur.
how can i fix this?
here is the link:
http://pascal.inf.uct.cl/~dip_chermosilla/testing/test.php
ps: sorry my english, i did my best.
October 19th, 2009 at 4:01 PM
Thanks for this. I’ve learned that if I add “buildinternet” to a lot of my google search queries I will find the solution to my problem.
Although this tutorial exists elsewhere in various forms yours in the best. The prose alone makes it a cut above the rest.
Thanks again
October 19th, 2009 at 9:57 PM
Hi again, while my previous comment still stands. I found that this plugin: http://labs.thesedays.com/projects/jquery/clearfield/ actually provides what your tutorial covers.
I do encourage learning and I learned some built in jQuery functions because of this but for ease of use. I specifically needed a different solution because I found that I needed to apply this to multiple fields all with different styles. So my code became cluttered and confusing quickly.
November 7th, 2009 at 1:41 PM
Colin thank you very much for the post with the clearfield i was about to ask them that question…. Awesome !
November 28th, 2009 at 6:39 PM
http://plugins.jquery.com/project/JQF1
Man! Look this form style plugin! It`s the most complete form style plugin! Works at IE 6 7 8, Safari (win and mac), firefox (win and mac), Opera, Chrome…
November 30th, 2009 at 11:26 PM
Thanks for this sample. Best regards.
December 13th, 2009 at 7:11 PM
———-snip———-
if (this.value == this.defaultValue){
this.value = ”;
}
if(this.value != this.defaultValue){
this.select();
}
———-snip———-
So, first, you check if they are equal, then again if they are not equal? you know, IF has a wellknown sibling called “ELSE”
December 20th, 2009 at 5:07 PM
To get working textarea I just did this $(‘input[type="text"],textarea’)
December 24th, 2009 at 5:46 PM
That worked for me aswell William,
and it saved at 666 bytes, scary stuff.
Join the Conversation!
Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.