Highlighting form fields with unobtrusive JavaScript

Freshness Warning
This article is over 12 years old. It's possible that the information you read below isn't current.

I wanted to alter the appearance of a form field when someone places their cursor in i, an effect that you see here and there.

My requirements for this were that I shouldn’t have to manually attach a Javascript event to every field and the code should be reusable on other sites without reconfiguration each time.

Using the principles of unobtrusive JavaScript I put together a short script, that when included on a page, will automatically add onFocus and onBlur handlers to all text and password fields on that page. When a field is activated it takes on the properties of a special CSS class. When it loses focus, it takes on the properties of another CSS class.

All you have to do to include this effect in your page is include the JavaScript file somewhere on the page and to add two CSS classes to your stylesheet. You decide how those CSS classes should make the form field look.

First, add the two CSS classes to your stylesheet and style them as you’d like. highlightActiveField is loaded when the field is activated. highlightInactiveField is loaded when the field loses focus.

.highlightActiveField {
    border: 1px solid black;
    border-left: 4px solid #BF1717;
    background-color: #DFDFDF;  
}

.highlightInactiveField {
    border: 1px solid black;    
    background-color: #fff;
}

Then add this JavaScript to the page somewhere—I created a file called highlightform.js and include it like this: <script type="text/javascript" src="highlightform.js"></script>

function initHighlight() {
    if (!document.getElementsByTagName){ return; }
    var allfields = document.getElementsByTagName("input");

    // loop through all input tags and add events
    for (var i=0; i<allfields.length; i++){
        var field = allfields[i];
        if ((field.getAttribute("type") == "text") || (field.getAttribute("type") == "password") ) {
            field.onfocus = function () {this.className = 'highlightActiveField';}
            field.onblur = function () {this.className = 'highlightInactiveField';}
        }
    }
}

// Nifty function to add onload events without overwriting
// ones already there courtesy of the lovely and talented
// Simon Willison http://simon.incutio.com/
function addLoadEvent(func) {   
    var oldonload = window.onload;
    if (typeof window.onload != 'function'){
        window.onload = func;
    } else {
        window.onload = function(){
        oldonload();
        func();
        }
    }
}

addLoadEvent(initHighlight);

Now step three... there is no step three! Just load your page and watch the magic.

Joseph Scott
July 19, 2006 9:19 PM

You can do this with plain CSS: input:focus, textarea:focus { background-color: yellow; } This works in Firefox, Opera and Safari. Of course IE doesn't properly support :focus on form fields :-(

Adam Kalsey
July 19, 2006 10:16 PM

Yes, since IE doesn't support the :hover pseudoclass on anything but links, it's neccessary to use JavaScript.

Jemaleddin
July 20, 2006 7:57 AM

You can also use Peter Nederlof's whatever:hover to add :hover, :focus and :active to IE: http://www.xs4all.nl/~peterned/csshover.html

Philip Tellis
July 29, 2006 1:51 AM

Problems: - If the textbox already has a class, your method overwrites it. - If the textbox already has onblur/onfocus event handlers, your method overwrites those. You know how to handle the latter. For the former, I'd suggest adding "highlightActiveField" to the className (.className += " highlightActiveField") onfocus and removing it onblur:.className = .className.replace(/ *highlightActiveField/g, '');

Dave
August 10, 2006 6:08 AM

This is pretty sweet, thanks for sharing.

trovster
August 17, 2006 7:25 AM

I threw the following together. It relies on some other functions, such as addClass, removeClass and addEvent. But it works for all form elements, not limiting to type="text" and type="password". The addEvent means events are not overwritten. And similarly addClass makes sure existing classes are not overwritten. Also, you do not need a default unfocused class, as you can simply use the element itself. input, textarea { border: 1px solid #ccc; } input.focused, textarea.focus_element { border-color: #000; } var focus_class = 'focus_element'; function form_focus_fix() { if(!document.createElement || !document.getElementsByTagName || !document.getElementById) return false; var form_collection = document.getElementsByTagName('form'); var form_collection_length = form_collection.length; for(i=0; i<form_collection_length; i++) { for(j=0; j<form_collection[i].elements.length; j++) { addEvent(form_collection[i].elements[j],'focus',function(){addClass(this,focus_class)}); addEvent(form_collection[i].elements[j],'blur',function(){removeClass(this,focus_class)}) } } }

This discussion has been closed.

Follow me on Twitter

Best Of

  • The mouse and me Not only is the mouse very destructive, but it's evaded all attempts to capture or kill it so far.
  • Comment Spam Manifesto Spammers are hereby put on notice. Your comments are not welcome. If the purpose behind your comment is to advertise yourself, your Web site, or a product that you are affiliated with, that comment is spam and will not be tolerated. We will hit you where it hurts by attacking your source of income.
  • The importance of being good Starbucks is pulling CD burning stations from their stores. That says something interesting about their brand.
  • Rounded corners in CSS There lots of ways to create rounded corners with CSS, but they always require lots of complex HTML and CSS. This is simpler.
  • Where do the RSS ad startups fit in? Yahoo's RSS advertising service could spell trouble for pure-play RSS advertising services unless they adapt their business model.
  • More of the best »

Recently Read

Get More

Subscribe | Archives

12

Recently

Stretching your team (Jun 11)
Stretching your team is one of the best ways to improve your output, your team's happiness, and your velocity. But they'll need coaching.
Physical camera shutter for Cisco Spark Board (Jul 6)
A 3d printable design for a camera shutter for a Cisco Spark Board
My Travel Coffee Setup (Jan 20)
What my travel coffee brewing setup looks like, and how you can build your own for under $100.
Turkey Legs (May 30)
Product naming gone awry.
Speaking for Geeks: Your Slides (Dec 17)
Tips and tricks for creating great slides.
Speaking for Geeks: Writing Your Talk (Dec 14)
Don’t wait until the night before the talk to write it. Crazy, I know.
Speaking for Geeks: Tell a Story (Dec 13)
Telling a story keeps your presentation focused, keeps your audience interested, and makes it easier for you to remember your talk.
Speaking for Geeks: Where to speak (Dec 11)
You've got a great idea for a talk. How do you find conferences to submit it to?

Subscribe to this site's feed.

Elsewhere

Tropo
Voice and communications platforms, including Tropo and Phono. Work.
SacStarts
The Sacramento technology startup community.
Pinewood Freak
Pinewood Derby tips and tricks

Contact

Adam Kalsey

Mobile: 916.600.2497

Email: adam AT kalsey.com

AIM or Skype: akalsey

Resume

PGP Key

©1999-2018 Adam Kalsey.
Content management by Movable Type.