Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Inobstrusive Form Field Highlighting in JavaScript
/*
* One of the recent problem that I ran across at work is an easy way to do highlighting for form fields.
* Of course the best way would be CSS 2
* (as shown here [http://www.cssdrive.com/index.php/examples/exampleitem/focus_pseudo_class/]) but alas,
* IE does not support that.
*
* The alternative is JavaScript onFocus and onBlur method. However, one thing which I also wanted to avoid
* is changing over 200 different pages in our system to add those in. So instead, I wrote a simple piece of
* Javascript which attaches the event handlers on the fly. The best part about this is that the actual form
* does not need to be changed - just include the Javascript on the bottom of your webpage. The code is as follows
*/
var fields = document.body.getElementsByTagName("INPUT");
for(i=0; i < fields.length; i++) {
if(fields[i].type == 'text' || fields[i].type == 'password') {
fields[i].onfocus = highlightOn;
fields[i].onblur = highlightOff;
}
}
/* The two highlight functions are as follows: */
function highlightOn() {
this.style.border = '1px solid blue';
this.style.backgroundColor = 'white';
}
function highlightOff() {
this.style.border = '1px groove #7A7E7C';
this.style.backgroundColor = '#EEEEEE';
}
/* And here is a real example */
var fields = document.body.getElementsByTagName("INPUT");
for(i=0; i < fields.length; i++) {
if(fields[i].type == 'text' || fields[i].type == 'password') {
fields[i].onfocus = highlightOn;
fields[i].onblur = highlightOff;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.