# Wednesday, August 04, 2010
« jQuery not running on the login page? Fi... | Main | CSS3 Pie – Make IE 6-8 render CSS3 decor... »

Normally forms don’t have much of a visual queue to the end user showing them where they are on a page.

image

Wouldn’t it be nice though?

image

That just seems like a step in the right direction.  Making this happen is a lot easier than I thought.  Most browsers can handle this with the css pseudo-class selector.  The css to make this happen for all your inputs would look like this:

input:focus
{
    background-color:LightYellow;
    border-color:Red;
    border-style:dotted;
    border-width:2px;
}

Pretty simple.  However, If you are need to support IE7 and lower the css above won’t do anything. IE7 doesn’t respect the focus selector.  Don’t fret. jQuery to the rescue.

if ($.browser.msie && $.browser.version == "7.0") {
    $("input").focus(function() {
        $(this).addClass('FocusFix');
    }).blur(function() {
      $(this).removeClass('FocusFix');
  });
}

Be sure to add the FocusFix class to your css:

input:focus, input.FocusFix
{
    background-color:LightYellow;
    border-color:Red;
    border-style:dotted;
    border-width:2px;
}

That should get you going in IE7.  You might notice though all your input types are doing this even buttons for example.  You can fix this by telling jQuery and css to select on certain types of inputs.

CSS:

input[type="text"]:focus, input[type="password"]:focus
And with jQuery:
if ($.browser.msie && $.browser.version == "7.0") {
  $("input[type='text'], input[type='password']").focus(function() {
      $(this).addClass('FocusFix');
  }).blur(function() {
    $(this).removeClass('FocusFix');
});

I have done all my targeting with the input element. You can just as easily have done this with classes for your elements. In my case, the application is already well underway and it seemed an easier approach to select the input types I wanted. You could also add your textareas easily this way.

Happy Coding!

OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: b, blockquote@cite, em, i, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview