Welcome to dtsn.co.uk, if your new here please subscribe to my feed
11/04/2008

This is quite a well known but under used technique for highlighting your form elements without any JavaScript. By using the CSS property focus you can apply style to a form element when it is clicked, also know as focus.

Example:

The HTML

The HTML is really simple all you need is a input box:

<input type="text" />

The CSS

The CSS can be approached by one of two ways you could either apply a class name to any form element which is applicable.

input:focus.yourclassname { background-color: red; }

Or you can use the CSS selectors to highlight every form like this.

input[type="text"]:focus { background-color: red; }

The focus selector only works in the modern browsers, and not IE7 and below. If you want this to be compatible with IE6 use this JavaScript, along with prototype

$$('input[type="text"]‘).each(function(element)) {
  Event.observe(element, ‘click’, function() {
    element.toggleClassName(’yourclassname’);
  });
});
kangax

that could be written even shorter:

$$(’input[type=text]‘).invoke(’observe’, ‘click’, function(el){ el.toggleClassName(’yourclassname’) })

Daniel

Hi Kangax,

Thats a great idea, I completely forgot about the Invoke method.

Daniel

Sashidhar Kokku

It does not work in IE7 either.

Daniel

Hi Sashidar,

Sorry I only have IE8 on my machine, and didn’t think to check IE7. I have now updated the post above, thanks for bringing it to my attention.

Daniel

Daily del.icio.us for April 6th through April 12th — Vinny Carpenter’s blog

[...] dtsn : Highlighting Forms [tutorial] - This is quite a well known but under used technique for highlighting your form elements without any JavaScript. By using the CSS property focus you can apply style to a form element when it is clicked, also know as focus. [...]

Reply