Files

Share

Topics

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.

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

&lt;style type="text/css"&gt;

*{

margin:0;

padding:0;

font:bold12px"Lucida Grande",Arial,sans-serif;

}

body{

padding:10px;

}

#status{

width:50%;

padding:10px;

outline:none;

height:36px;

}

.focusField{

border:solid2px#73A6FF;

background:#EFF5FF;

color:#000;

}

.idleField{

background:#EEE;

color:#6F6F6F;

border:solid2px#DFDFDF;

}

&lt;/style&gt;

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

$(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

1

$('input[type="text"]').addClass("idleField");

When a text input gets focus, remove the inactive style and add the active style.

1

2

3

$('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.

1

2

3

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.

1

2

3

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.

1

2

3

4

5

6

$('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.

100 Comments 87 Mentions

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.

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)

@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

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?

@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.

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.

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.

@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”);
}
});

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.

@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!

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

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.

Hey there, looking for something like this that uses jQuery for a commercial project, and thought I’d just jump on and say that for some unknown reason, this causes errors in the jquery min file in versions 1.4.1 and 1.4.2. :(

Everyone seems to be saying that the :focus pseudo class doesn’t work for IE 6. Um….. has anyone noticed it doesn’t work for IE 7 either? kinda hard to make professional web sites and not support IE 7. That’s where this piece of code comes in real handy. Thanks for doing it!

(couldn’t resist throwing a CSS3 shadow on the focused field)
However I’ve now reached the far end of my javaScript skills and I’m wondering if anyone can recommend a good validation script that will work along with this setup?

Seeing as how we should always try to keep CSS dominant…
Specify a class to add onFocus, but not an idle one (keep that one as default CSS state for inputs, don’t reply on JS to add the style.
Strip the class when you leave focus.

You have a great Google rank for this topic, so thanks for the relevant content :)

This might have been mentioned before. In response to Razvan at the beginning of the comment thread, you indicated that the only issue (besides IE6 compatibility) keeping you from using pure CSS is that the placeholder text would not appear/disappear properly without Javascript.

All modern browsers, however, have now implemented HTML’s ‘placeholder’ attribute in form input fields. You don’t even need Javascript to get fully working placeholder text.

So if one wishes to go pure HTML/CSS, it can be fully replicated without Javascript, although it will only work in relatively modern browsers.