dtsn · I build cool stuff for the web. Hi I'm Daniel and I blog about design, JavaScript and CSS. Find out more about me and subscribe to my feed.
11 Apr

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]

No Comments

  • kangax 11/04/2008

    that could be written even shorter:

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

  • Daniel 11/04/2008

    Hi Kangax,

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

    Daniel

  • Sashidhar Kokku 11/04/2008

    It does not work in IE7 either.

  • Daniel 11/04/2008

    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

  • Permalink
    Daily del.icio.us for April 6th through April 12th — Vinny Carpenter’s blog 12/04/2008

    [...] 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. [...]

  • ricky C. 23/07/2008

    Hi,
    For us dummies who don’t know how to use prototype… can you explain exactly where this javascript code gets added? thanks! :)

  • Daniel 24/07/2008

    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

Reply