Highlighting Forms
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:
[code="html"]
[/code]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.
[code="css"]
input:focus.yourclassname { background-color: red; }
[/code]
Or you can use the CSS selectors to highlight every form like this.
[code="css"]
input[type="text"]:focus { background-color: red; }
[/code]
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
[code="javascript"]
$$('input[type="text"]').each(function(element)) {
Event.observe(element, 'click', function() {
element.toggleClassName('yourclassname');
});
});
[/code]




that could be written even shorter:
$$(‘input[type=text]‘).invoke(‘observe’, ‘click’, function(el){ el.toggleClassName(‘yourclassname’) })
Hi Kangax,
Thats a great idea, I completely forgot about the Invoke method.
Daniel
It does not work in IE7 either.
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
[...] 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. [...]
Hi,
For us dummies who don’t know how to use prototype… can you explain exactly where this javascript code gets added? thanks!
Hi Ricky C,
If you just want to highlight some forms then you don’t need the entire prototype library. You can achieve the same in plain JavaScript.
The best way to add the library is to get it from the Google Hosted version. To do this you just need to add:
Into the HEAD section of your HTML page